其本质还是把异常交给SpringMVC框架来处理 系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
1.使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver 2.实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
处理逻辑:使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver,处理器实现HandlerExceptionResolver 接口,全局异常处理器需要实现该接口 **SimpleMappingExceptionResolver:**就是通过简单的映射关系来决定由哪个视图,来处理当前的错误信息。 **SimpleMappingExceptionResolver:**提供通过异常类型exceptionMappings,来进行异常与视图之间的映射关系,提供在发生异常时,通过statusCodes来映射异常返回的视图名称和对应的HttpServletResponse的返回码。而且可以通过defaultErrorView和defaultErrorCode来指定默认值,defaultErrorView表示当没有在exceptionMappings里面找到对应的异常类型时,就返回defaultErrorView定义的视图,defaultErrorCode表示在发生异常时,当没有在视图与返回码的映射关系statusCodes里面找到对应的映射时,默认返回的返回码。 在使用SimpleMappingExceptionResolver时,当发生异常的时候,SimpleMappingExceptionResolver将会把当前的异常对象放到自身属性exceptionAttribute中,当没有指定exceptionAttribute时,exceptionAttribute就是用默认值exception
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!--默认错误视图--> <!--即找不到默认的错误类型的时候就默认使用这个--> <property name="defaultErrorView" value="defaulterror"/> <!--具体类型报错的错误视图--> <property name="exceptionMappings"> <map> <entry key="java.lang.ClassCastException" value="ClassCastException"/> </map> </property> </bean>2.1实现HandlerExceptionResolver
package com.pjh.Myexception; import com.sun.org.apache.bcel.internal.generic.MONITORENTER; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyexceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(); if (e instanceof MyEcxeption){ //对于自定义异常的操作 }else{ //对于非自定义异常的操作 } return modelAndView; } }2.2在配置文件中配置
<bean class="com.pjh.Myexception.MyexceptionResolver"/>