springmvc利用HandlerExceptionResolver处理程序的异常,包括处理映射映射异常,数据绑定,处理器执行过程中发生的异常
public interface HandlerExceptionResolver {
ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}
当发生异常的时候,直接调用resolveException,生成一个modelandview报告给用户
HandlerExceptionResolver 的实现类默认有四个
1.DefaultHandlerExceptionResolver 默认已经安装,他会直接将异常转化成相应的响应状态码,可以在web.xml配置状态,转到响应的异常处理页面
<error-page>
<error-code>403</error-code>
<location>/WEB-INF/jsp/error/403.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/error/404.jsp</location>
</error-page>
<error-page>
<error-code>405</error-code>
<location>/WEB-INF/jsp/error/405.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
2.AnnotationMethodHandlerExceptionResolver 默认已经安装,可以通过注解的方式处理异常
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public String handlerException(){
return "task/error";
}
@ExceptionHandler可以指定监听哪个异常类型,如果不指定,则默认不监听任何异常
3.SimpleMappingExceptionResolver 可以对异常统一处理,然后既爱那个异常类异常为视图名,发生错误时,可以把异常报告给用户,我们可以利用它来自定义异常处理。
public class CustomerExceptionHandler extends SimpleMappingExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
String viewName = determineViewName(exception, request);
if (viewName != null) {
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With")!= null && request
.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {//非异步请求
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
applyStatusCodeIfPossible(request, response, statusCode);
}
return getModelAndView(viewName, exception, request);
} else {//异步请求的话,发生异常则直接把异常写到输出流中,将ModelAndView置为空,则springmvc不处理response
try {
PrintWriter print = response.getWriter();
print.write(exception.getMessage());
print.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
} else {
return null;
}
}
}
我们这里自定义了一个异常处理器,可以处理异步请求发生的异常,然后我们把自定义的异常处理注册到springmvc中
<bean class="com.liuxg.util.exception.CustomerExceptionHandler">
<property name="exceptionMappings">
<props>
<prop key="com.liuxg.util.exception.SystemException">task/task</prop>
</props>
</property>
</bean>
这里我们还可以自定义一些异常映射处理类,例如,我们自己定义SystemException异常处理类
@SuppressWarnings("serial")
public class SystemException extends Exception {
public SystemException(String msg) {
super(msg);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException(String msg, Throwable cause) {
super(msg, cause);
}
}
然后我们在程序中就可以抛出自己定义的异常类别,然后交由我们自定义的处理器进行处理
@RequestMapping("/mvcTest1")
public void mvcTest1() throws SystemException{
throw new SystemException("系统异常");
}