Springboot拦截异常并同统一处理

@ControllerAdvice注解,可以用于定义@ExceptionHandle,@InitBinder,@ModelAttribute,并应用到所有的@ResquestMapping中。
请看代码:
/**

  • 统一异常处理类

  • 捕获程序所有异常,针对不同异常,采取不同的处理方式

  • @author zjjlive)

  • @version 1.0

  • @website https://www.foreknow.me

  • @date 2018/4/24 14:37

  • @since 1.0
    */
    @ControllerAdvice
    public class ExceptionHandleController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandleController.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseVO handle(Throwable e) {
    if (e instanceof ZhydException) {
    return ResultUtil.error(e.getMessage());
    }
    if (e instanceof UndeclaredThrowableException) {
    e = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
    }
    ResponseStatus responseStatus = ResponseStatus.getResponseStatus(e.getMessage());
    if (responseStatus != null) {
    LOGGER.error(responseStatus.getMessage());
    return ResultUtil.error(responseStatus.getCode(), responseStatus.getMessage());
    }
    e.printStackTrace(); // 打印异常栈
    return ResultUtil.error(CommonConst.DEFAULT_ERROR_CODE, ResponseStatus.ERROR.getMessage());
    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容