我有enum
类ErrorCode
,它有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"
}
我们能实现这样的东西吗
2条答案
按热度按时间s6fujrry1#
1.通过扩展
ResponseStatusException
类创建自定义异常 Package 器。样品;如果你需要更多的权力在你的例外;
1.创建一个类并添加
@ControllerAdvice
,通过扩展ResponseEntityExceptionHandler
来全局处理所有异常。1.使用
@ExceptionHandler(CustomException.class)
处理CustomException
并实现该方法。你可以简单地跳过第2和第3部分,因为你在Sping Boot 应用程序上抛出
ResponseStatusException
类型,它会自动捕获异常并相应地抛出它。您可以从LINK1和LINK2中了解更多信息jexiocij2#
实际上,我发现了一个类似的方法,我想实现。https://stackify.com/java-custom-exceptions/#:~:text= Custom%20exceptions%20provide%20you%20the,the%20exception%20to%20a%20user.