标签:exce err stc handler ref 异常捕获 lan tutorial view
项目的说明
MyExceptionHandler.java
@ControllerAdvice
public class MyExceptionHandler {
public static final String ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace();
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ERROR_VIEW);
return mav;
}
}
MyAjaxExceptionHandler.java
@RestControllerAdvice
public class MyAjaxExceptionHandler {
@ExceptionHandler(value = Exception.class)
public JsonResult defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
e.printStackTrace();
return JsonResult.errorException(e.getMessage());
}
}
注意在验证这一步时,把MyExceptionHandler.java这个类给注释了,因为如果不注释的话,两个类都会拦截Exception了。
下面在MyExceptionHandler.java的基础上配置
MyExceptionHandler.java
@RestControllerAdvice
public class MyExceptionHandler {
public static final String ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace();
if (isAjax(request)) {
return JsonResult.errorException(e.getMessage());
} else {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ERROR_VIEW);
return mav;
}
}
// 判断是否是ajax请求
public static boolean isAjax(HttpServletRequest httpRequest) {
String xRequestedWith = httpRequest.getHeader("X-Requested-With");
return (xRequestedWith != null && "XMLHttpRequest".equals(xRequestedWith));
}
}
参照上两步的验证,验证前先把MyAjaxExceptionHandler.java给注了。
# 注意区分
# 在类上的注解
@ControllerAdvice
@RestControllerAdvice
# 在方法上的注解
@ExceptionHandler(value = Exception.class)
# 在统一返回异常的形式配置中
类上的注解为@RestControllerAdvice
方法中返回ModelAndView对象就是返回页面,返回一个其他对象就会转换为json串,这样就实现了对页面请求和ajax请求中的错误的统一处理。
标签:exce err stc handler ref 异常捕获 lan tutorial view
原文地址:https://www.cnblogs.com/okokabcd/p/9175797.html