每天学点SpringMVC-异常处理

1. 第一步先写个Hello World

    1.1 编写一个抛出异常的目标方法

 @RequestMapping("/testException.do")
    public String testException(){
        int i = 1 / 0 ;
        return "index" ;
    }

    1.2 当前Controller中添加@ExceptionHandler标记方法

@ExceptionHandler(value = {ArithmeticException.class})
    public ModelAndView handleArithException(Exception ex){
        ModelAndView mv = new ModelAndView("error") ;
        mv.addObject("ex",ex) ;
        return mv ;
    }

 1.3 加上error界面

 

    1.4 测试结果

   1.5 总结一下

         1)@ExceptionHandler标记的方法在目标方法发生对应的异常触发,传入的参数Exception即为对应的异常对象

         2)不能通过参数中添加Map的形式将异常对象传递的界面,需要用ModelAndView的形式实现

         3)优先级:优先在当前Controller中@ExceptionHandler标记的方法,如果有多个,谁标记的异常越接近,则选择谁,如果当前Controller没有匹配到,则在@ControllerAdvice标记的类中找@ExceptionHandler标记的方法

2. @ResponseStatus注解能够实现目标异常产生时,反馈给client端指定的状态码跟信息

   2.1 构建目标异常并添加@ResponseStatus注解

@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "test")
public class TestException extends RuntimeException {
}

  2.2 构建测试RequestMapper

 @RequestMapping("/testResponseStatus.do")
    public String testResponseStatus(){
        throw new TestException() ;
    }

   2.3 测试结果如下

    2.4 如果指定异常被ExceptionHandler捕获时,发生什么?

    1)在上述ExceptionHandler中添加TextException

   2)重新部署测试结果

3. 可通过spring-mvc.xml配置ExceptionResolver实现指定异常发送跳转到指定页面

    3.1 定义指定异常

public class TestDefaultException extends RuntimeException {
}

 

    3.2 spring-mvc.xml中进行配置

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error"></property>
        <property name="exceptionAttribute" value="ex"/>
        <property name="exceptionMappings">
            <props>
                <prop key="com.pawn.crud.exceptions.TestDefaultException">error</prop>
            </props>
        </property>
    </bean>

 

  3.3 测试

@RequestMapping("/testDefaultException.do")
    public String testDefaultException(){
        throw new TestDefaultException() ;
    }

 3.4 有个小坑:指定的异常不能加@ResponseStatus注解,否则配置的ExceptionResolver会失效

 

demo:https://github.com/705645051/demoCrud

 

posted @ 2017-09-26 21:57  Xpawn  阅读(162)  评论(0编辑  收藏  举报