SpringBoot之异常处理(就看这篇够了!)

让我详细解释 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. 注意事项

异常处理层次:

  1. 方法级(@ExceptionHandler在Controller中)
  2. 类级(@ControllerAdvice全局)
  3. 默认处理(SpringBoot默认异常处理器)

@ExceptionHandler 可以:

  1. 自定义返回内容
  2. 进行额外的处理(如日志)
  3. 更灵活的异常处理

@ResponseStatus 主要用于:

  1. 设置HTTP状态码
  2. 简单的异常处理
  3. 作为补充配置

最佳实践:

  1. 简单异常用 @ResponseStatus
  2. 需要自定义处理的用 @ExceptionHandler
  3. 可以组合使用两者,获得更好的控制


 

希望对各位看官有所帮助,如果能得到您的一个赞,那就太荣幸了,下期见,谢谢~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值