美文网首页
springboot异常全局处理

springboot异常全局处理

作者: 飘_摇_ | 来源:发表于2019-12-03 10:23 被阅读0次
处理除404的其他异常
/**
 * 只能拦截进入控制器后发生的异常,对于404这种不进入控制器处理的异常不起作用
 */
@RestControllerAdvice
public class DefaultExceptionHandler {

    Logger logger = LoggerFactory.getLogger(DefaultExceptionHandler.class);
    private static final String ERROR_PATH = "error";
    @ExceptionHandler({Exception.class})
    public Object handleException(Exception e, HttpServletRequest request) {
        e.printStackTrace();
        //如果是ajax请求则返回错误描述
        if (HttpUtil.jsAjax(request)) {
            return R.error(500, "服务器错误,请联系管理员");
        }
        ModelAndView modelAndView=new ModelAndView(ERROR_PATH +"/500");
        modelAndView.addObject("msg",e.getMessage());
        return modelAndView;
    }

}
处理404异常
/**
 * 只处理404错误
 */
@Controller
public class ErrorPageController implements ErrorController {

    private static final String ERROR_PATH = "error";

    @RequestMapping(ERROR_PATH)
    public String error(HttpServletRequest request){
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        System.out.println(statusCode);
        if(statusCode==404){
            return ERROR_PATH+"/404";
        }
        return ERROR_PATH+"/500";
    }
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
判断是否为ajax请求
public static boolean jsAjax(HttpServletRequest req){
     //判断是否为ajax请求,默认不是
     boolean isAjaxRequest = false;
     if(!StringUtils.isEmpty(req.getHeader("x-requested-with")) && req.getHeader("x-requested-with").equals("XMLHttpRequest")){
         isAjaxRequest = true;
     }
     return isAjaxRequest;
 }

相关文章

网友评论

      本文标题:springboot异常全局处理

      本文链接:https://www.haomeiwen.com/subject/eezxgctx.html