Spring MVC处理异常有3种方式:
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理;
1. 集成异常处理
使用SimpleMappingExceptionResolver实现异常处理
1、在Spring的配置文件springMVC.xml中增加以下内容:
error-business
error-parameter
2.实现HandlerExceptionResolver 接口自定义异常处理器
增加HandlerExceptionResolver 接口的实现类MyExceptionHandler,代码如下:
public class MyExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
Map model = new HashMap();
model.put("ex", ex);
// 根据不同错误转向不同页面
if(ex instanceof BusinessException) {
return new ModelAndView("error-business", model);
}else if(ex instanceof ParameterException) {
return new ModelAndView("error-parameter", model);
} else {
return new ModelAndView("error", model);
}
}
}
2、在Spring的配置文件springMVC.xml中增加以下内容:
3.使用@ExceptionHandler注解实现异常处理
增加CrowdExceptionResolver 类,并在类中使用@ExceptionHandler注解声明异常处理,代码如下:
public class CrowdExceptionResolver {
/**
* 空指针异常
*/
@ExceptionHandler(value = NullPointerException.class)
public ModelAndView resolverNullPointerException(NullPointerException exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
return commonResolver("system-error", exception,request,response);
}
/**
* 数学异常
*/
@ExceptionHandler(value = ArithmeticException.class)
public ModelAndView resolverNullPointerException(ArithmeticException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println(e.getMessage());
return commonResolver("system-error", e,request,response);
}
/**
* 通用异常处理
* @param viewName 跳转视图名字
* @param e 异常类型
* @param request 请求
* @param response 响应
* @return
* @throws IOException
*/
protected ModelAndView commonResolver(String viewName ,Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean requestJson = CrowdUtil.isRequestAjax(request);
if (requestJson){//Ajax请求
ResultEntity
2、修改代码,使所有需要异常处理的Controller都继承该类,如下所示,修改后的TestController类继承于BaseController:
public class TestController extends CrowdExceptionResolver