异常处理

108 阅读1分钟

SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver

HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver

DefaultHandlerExceptionResolver 如果在控制器方法执行过程中出现了指定的异常,就可以返回一个新的ModelAndview来代替原来要返回的ModelAndView

SimpleMappingExceptionResolver自定义处理异常

SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:

  • 基于配置的异常处理
<!--配置异常-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <!--properties的键表示处理器方法执行过程中出现的异常
                properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定的页面-->
            <prop key="java.lang.ArithmeticException">error</prop>
        </props>
    </property>
    <!--这里以value为键 ,以当前的异常为值-->
    <property name="exceptionAttribute" value="ex"></property>
</bean>
  • 基于注解的处理
@ControllerAdvice  //包含了controller的功能
public class ExceptionController {
    //如果出现value中指定的异常就会执行 注解的方法
    @ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
    //形参中的exeption就是当前出现的异常
    public String testException(Exception exception){
        return "error";
    }
}