Spring 统一异常处理

113 阅读1分钟

使用统一异常处理前,在Controller里需要处理各种异常,看起来很不舒服,而且不方便维护。

image.png

使用统一异常处理后,可以把try-catch全部去掉,看起来清晰多了。

image.png

这里以处理IllegalArgumentException这种异常为例,加到统一异常处理拦截器中,其他类型的异常可以在切面中添加类似的方法即可。

@ControllerAdvice
@ResponseBody
public class AUnifiedException {
    Logger LOGGER = LoggerFactory.getLogger(AUnifiedException.class);

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//指定HTTP响应的状态码,可以不要
    @ExceptionHandler(IllegalArgumentException.class)//要处理的异常类型
    @ResponseBody
    public ApiResponse handlerIllegalArgumentException(IllegalArgumentException e) {
        LOGGER.error(e.getMessage(), e);
        return ApiResponse.FAIL(e.getMessage());
    }



}