码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot自定义异常处理

时间:2021-07-05 17:45:41      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:lock   stack   int   tst   ack   turn   one   run   rri   

全局异常处理

@ControllerAdvice
@RestController
public class GlobalExceptionInterceptor {
?
    //Exception异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){
        e.printStackTrace();
        LogUtil.writeLog("error","log",e.getMessage()+e.getStackTrace());
        Result result = Result.errorResult();
        if (e.getClass().equals(HttpMediaTypeNotSupportedException.class)){
            result.setCode(-981);
            result.setMsg("请求参数格式错误");
        }else{
            result.setCode(-998);
            result.setMsg("系统执行发生错误");
        }
?
        return result;
    }
?
    //运行时异常
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result exceptionHandler(RuntimeException e){
        e.printStackTrace();
        LogUtil.writeLog("error","log",e.getMessage()+e.getStackTrace());
        Result result = Result.errorResult();
        result.setCode(-997);
        result.setMsg("系统运行发生错误");
        return result;
    }
?
}

全局404拦截

@Component
public class ResponseStatusInterceptor implements HandlerInterceptor {
?
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(response.getStatus()==404){
            response.sendRedirect(request.getContextPath() + "/frame/error/404");
        }
        return true;
    }
?
}

SpringBoot自定义异常处理

标签:lock   stack   int   tst   ack   turn   one   run   rri   

原文地址:https://www.cnblogs.com/yanpeng19940119/p/14965888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!