spring boot 中统一异常处理

时间:2022-03-29 15:25:37

基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常

步骤一:自定义异常类

public class UserNotExistException extends RuntimeException{
private static final long serialVersionUID = -1574716826948451793L; private String id; public UserNotExistException(String id){
super("user not exist");
this.id = id;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
}
}

步骤二:定义异常处理类

@ControllerAdvice
public class ControllerExceptionHandler { @ExceptionHandler(UserNotExistException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> handleUserNotExistsException(UserNotExistException e) {
Map<String, Object> map = new HashMap<>();
map.put("id", e.getId());
map.put("message", e.getMessage());
return map;
}
}

步骤三:控制层抛出异常

  @GetMapping("/{id:\\d+}")
public void get(@PathVariable String id) {
throw new UserNotExistException(id);
}