java 如何枚举错误代码和消息与自定义例外集成

x4shl7ld  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(97)

我有enumErrorCode,它有ID和消息,如下所示:

public enum ErrorCode {

    SECURITYCODE_NOT_PROVIDED(452, "security code required"),
    
    CARD_ALREADY_EXIST_FOR_USERID(453,"Card Number already exist for provided userId");

    private final int id;
    private final String message;

    ErrorCode(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

我需要创建自定义的RuntimeException,并将ErrorCode传递给该构造函数,并获得如下输出响应,当securityCode为空时需要trow该自定义异常

控制器类

@RequestMapping("/api/user")
    @RestController
    public class UserController {
    
    @PostMapping("/add")
        public ResponseEntity<?> add(
                @RequestParam("userId") long userId, @RequestParam("userName") String userName,
                @RequestParam("securityCode") String securityCode) throws CustomException{
            
            User user= userService.add(userId, userName, securityCode);
            return new ResponseEntity<>(user, HttpStatus.OK);
        }
    }

服务等级

public User add(userId, userName, securityCode) throws CustomException {
    if(!user.securityCode.isEmpty() && user.securityCode.equals !=""){
        //implementation
    }
    else{
        threw new CustomException(SECURITYCODE_NOT_PROVIDED);
    }
}

预期响应:

{
    "timestamp": 1550987372934,
    "status": 452,
    "error": "security code required",
    "exception": "com.app.exception.CustomException",
    "message": "security code required",
    "path": "/api/user/add"
}

我们能实现这样的东西吗

s6fujrry

s6fujrry1#

1.通过扩展ResponseStatusException类创建自定义异常 Package 器。样品;

public class CustomException extends ResponseStatusException {

public CustomException (ErrorCode errorCode) {
   super(errorcode.getId(),errorCode.getMessage());
}

 public CustomException (ErrorCode errorCode, Exception ex) {
   super(errorcode.getId(),errorCode.getMessage(),ex);
}
}

如果你需要更多的权力在你的例外;
1.创建一个类并添加@ControllerAdvice,通过扩展ResponseEntityExceptionHandler来全局处理所有异常。
1.使用@ExceptionHandler(CustomException.class)处理CustomException并实现该方法。
你可以简单地跳过第2和第3部分,因为你在Sping Boot 应用程序上抛出ResponseStatusException类型,它会自动捕获异常并相应地抛出它。您可以从LINK1LINK2中了解更多信息

jexiocij

jexiocij2#

实际上,我发现了一个类似的方法,我想实现。https://stackify.com/java-custom-exceptions/#:~:text= Custom%20exceptions%20provide%20you%20the,the%20exception%20to%20a%20user.

相关问题