SpringBoot 统一异常处理
1.在SpringBoot中项目中常见的统一异常处理方式是:使用@RestControllerAdvice和@ExceptionHandler注解。项目中的所有类型异常都会被抛到统一异常处理类中统一处理。预期效果如下:
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;
}
}
- 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类进行手动抛出。如下:
我把代码复制出来,如下:
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
resolver.resolveException(httpRequest, httpResponse, null, e);