SpringBoot 统一异常处理

1.在SpringBoot中项目中常见的统一异常处理方式是:使用@RestControllerAdvice和@ExceptionHandler注解。项目中的所有类型异常都会被抛到统一异常处理类中统一处理。预期效果如下:

image

2.新建一个异常类ParamValidException,继承RuntimeException.

复制@Data
public class ParamValidException extends RuntimeException {

    /**
     * 异常错误码
     */
    private int code ;

    /**
     * 异常信息
     */
    private String msg ;

    /**
     * Constructs a new runtime exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public ParamValidException(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }


}
  1. GlobalExceptionHandler类:
复制@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 统一异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception e){
        return Result.ERROR(e.getLocalizedMessage());
    }


    /**
     * 参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = ParamValidException.class)
    public Result paramErrorHandler(ParamValidException e){
        return Result.ERROR(e.getCode() ,e.getMsg());
    }



}

4.不过,在Filter过滤器中的异常是无法被抛到统一异常处理类中,需要借助于HandlerExceptionResolver类进行手动抛出。如下:

image

我把代码复制出来,如下:

复制    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;
	
	
    resolver.resolveException(httpRequest, httpResponse, null, e);
posted @   xiaobiao~  阅读(84)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
点击右上角即可分享
微信分享提示