SpringBoot的异常处理
全局异常处理
对整个项目的异常进行自动拦截处理,方便以后抛出自定义异常
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @RestControllerAdvice @Slf4j public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public String MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) { ObjectError objectError = e.getBindingResult().getAllErrors().get(0); return ResponseEntity.failed(objectError.getDefaultMessage()); }
@ExceptionHandler(Exception.class) public ResponseEntity exceptionHandler(Exception e){ log.error("出现了异常! {}",e); return ResponseEntity.failed(e.getMessage()); } }
|
自定义异常
方便携带更多的错误信息如状态码等..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Getter public class APIException extends RuntimeException { private int code; private String msg;
public APIException() { this(XXX, "接口错误"); }
public APIException(String msg) { this(XXX, msg); }
public APIException(int code, String msg) { super(msg); this.code = code; this.msg = msg; } }
|
交给全局异常处理解决:
1 2 3 4 5 6
| @ExceptionHandler(APIException.class) public String APIExceptionHandler(APIException e) { log.error("出现了异常! {}",e); return ResponseEntity.failed(e.getMsg()); }
|
ResponseEntity为统一的响应实体方便与前端联调
参考