处理除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;
}