SpringMVC--异常处理

1.ExceptionHandlerExceptionResolver(主要处理 Handler 中用 @ExceptionHandler 注解定义的方法)

  (1) 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象

@RequestMapping("/testException")
public String testException(@RequestParam("i") Integer i){
    System.out.println("--->"+10/i);
    return "success";
}

  (2) @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值

@ExceptionHandler({ArithmeticException.class})
public ModelAndView handleException(Exception e){
    System.out.println("异常-->"+e);
    ModelAndView modelAndView = new ModelAndView("error");
    modelAndView.addObject("exception",e);
    return modelAndView;
}

  (3) @ExceptionHandler 方法标记的异常有优先级的问题.
  (4) @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常,则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.

@ControllerAdvice
public class exceptions {

    @ExceptionHandler({ArithmeticException.class})
    public ModelAndView handleException(Exception e){
        System.out.println("异常-->"+e);
        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("exception",e);
        return modelAndView;
    }
}

2.ResponseStatusExceptionResolver(在异常及异常父类中找到 @ResponseStatus 注解,用这个注解的属性进行处理)

  定义一个 @ResponseStatus 注解修饰的异常类

@ResponseStatus(value= HttpStatus.FORBIDDEN, reason="用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extends RuntimeException{
    private static final long serialVersionUID = 1L;
}

3.DefaultHandlerExceptionResolver (对一些特殊的异常进行处理)

4.SimpleMappingExceptionResolver(将异常类名映射为视图名,即发生异常时使用对应的视图报告异常)

<!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
        </props>
    </property>
</bean>
发布了121 篇原创文章 · 获赞 45 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/102573761