让我详细解释 SpringBoot 中的三种异常处理方式。
执行顺序:局部异常>全局异常>默认异常处理机制!!!
1. 局部异常处理(@ExceptionHandler)
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 局部异常处理,只对当前Controller有效
*/
@ExceptionHandler(IllegalArgumentException.class)
public ResponseResult handleIllegalArgumentException(IllegalArgumentException e) {
log.error("参数校验异常", e);
return ResponseResult.error("参数错误:" + e.getMessage());
}
/**
* 可以处理多个异常
*/
@ExceptionHandler({NullPointerException.class, IndexOutOfBoundsException.class})
public ResponseResult handleRuntimeException(RuntimeException e) {
log.error("运行时异常", e);
return ResponseResult.error("系统错误:" + e.getMessage());
}
}
2. 全局异常处理(@RestControllerAdvice)
@RestControllerAdvice // 也可以用@ControllerAdvice
@Order(0) // 可以设置优先级,数字越小优先级越高
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理参数校验异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult handleValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return ResponseResult.error("参数错误:" + message);
}
/**
* 处理业务异常
*/
@ExceptionHandler(BusinessException.class)
public ResponseResult handleBusinessException(BusinessException e) {
log.warn("业务异常:", e);
return ResponseResult.error(e.getCode(), e.getMessage());
}
/**
* 处理所有未捕获的异常
*/
@ExceptionHandler(Exception.class)
public ResponseResult handleException(Exception e) {
log.error("系统异常:", e);
return ResponseResult.error("系统繁忙,请稍后重试");
}
}
3. 自定义异常(@ResponseStatus)
@ExceptionHandler注解的异常优先于@ResponseStatus注解的异常
原因:局部异常>全局异常>默认异常处理机制
如果异常被@ExceptionHandler捕捉到了,就不会走默认机制输出@ResponseStatus所带的内容
/**
* 方式1:使用@ResponseStatus注解
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "自定义异常")
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
/**
* 方式2:更灵活的自定义异常
*/
public class BusinessException extends RuntimeException {
@Getter
private String code;
@Getter
@ResponseStatus(HttpStatus.BAD_REQUEST) // 可以在属性上使用
private HttpStatus status;
public BusinessException(String code, String message) {
super(message);
this.code = code;
this.status = HttpStatus.BAD_REQUEST;
}
}
4. 注意事项
异常处理层次:
- 方法级(@ExceptionHandler在Controller中)
- 类级(@ControllerAdvice全局)
- 默认处理(SpringBoot默认异常处理器)
@ExceptionHandler 可以:
- 自定义返回内容
- 进行额外的处理(如日志)
- 更灵活的异常处理
@ResponseStatus 主要用于:
- 设置HTTP状态码
- 简单的异常处理
- 作为补充配置
最佳实践:
- 简单异常用 @ResponseStatus
- 需要自定义处理的用 @ExceptionHandler
- 可以组合使用两者,获得更好的控制
希望对各位看官有所帮助,如果能得到您的一个赞,那就太荣幸了,下期见,谢谢~

被折叠的 条评论
为什么被折叠?



