0
点赞
收藏
分享

微信扫一扫

Springboot拦截异常并同统一处理

奋斗De奶爸 2021-09-24 阅读 79
日记本

@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());
    }

}

举报

相关推荐

0 条评论