一、简介

• Spring MVC 通过 HandlerExceptionResolver 处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。
• SpringMVC 提供的 HandlerExceptionResolver 的实现类

• DispatcherServlet 默认装配的 HandlerExceptionResolver :
– 没有使用 <mvc:annotation-driven/> 配置:

– 使用了 <mvc:annotation-driven/> 配置:

二、ExceptionHandlerExceptionResolver

在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
@ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
@ExceptionHandler 方法标记的异常有优先级的问题.
@ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 则将去 @ControllerAdvice 标记的类中查找@ExceptionHandler 标记的方法来处理异常.

1. 编写异常handle

     @ExceptionHandler({RuntimeException.class})
public ModelAndView handleArithmeticException2(Exception ex){
System.out.println("[出异常了]: " + ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
} ////优先级高于handleArithmeticException2,如果没有找到具体的异常就使用handleArithmeticException2
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception ex){
System.out.println("出异常了: " + ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
} @RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
System.out.println("result: " + (10 / i));
return "success";
}

2.在jsp页面发送请求

 <a href="testExceptionHandlerExceptionResolver?i=0">Test ExceptionHandlerExceptionResolver</a>

3. 编写错误回显的页面error.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <h4>Error Page</h4> ${requestScope.exception } </body>
</html>

备注:

如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 则将去 @ControllerAdvice 标记的类中查找@ExceptionHandler 标记的方法来处理异常.

 @ControllerAdvice
public class SpringMVCTestExceptionHandler { @ExceptionHandler({ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception ex){
System.out.println("----> 出异常了: " + ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
} }

三、ResponseStatusExceptionResolver

在异常及异常父类中找到 @ResponseStatus 注解,然后使用这个注解的属性进行处理。

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

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

2.编写handle

使用@ResponseStatus标注的方法即使没有异常也会报异常

 @ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if(i == 13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver..."); return "success";
}

3.在jsp页面发送请求

 <a href="testResponseStatusExceptionResolver?i=13">Test ResponseStatusExceptionResolver</a>

使用@ResponseStatus标注的方法即使没有异常也会报异常

四、DefaultHandlerExceptionResolver

对一些特殊的异常进行处理,比如NoSuchRequestHandlingMethodException、HttpRequestMethodNotSupportedException、HttpMediaTypeNotSupportedException、HttpMediaTypeNotAcceptableException等

1.编写handle

 @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
public String testDefaultHandlerExceptionResolver(){
System.out.println("testDefaultHandlerExceptionResolver...");
return "success";
}

2.在jsp页面发送请求

 <a href="testDefaultHandlerExceptionResolver">Test DefaultHandlerExceptionResolver</a>

五、SimpleMappingExceptionResolver

如果希望对所有异常进行统一处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常

1. 在springmvc.xml配置SimpleMappingExceptionResolver,配置异常的名字exceptionAttribute和异常回显的页面exceptionMappings


 <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"></property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>

2. 编写handle

 @RequestMapping("/testSimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
String [] vals = new String[10];
System.out.println(vals[i]);
return "success";
}

3.在jsp页面发送请求

 <a href="testSimpleMappingExceptionResolver?i=12">Test SimpleMappingExceptionResolver</a>

4.错误回显页面error.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <h4>Error Page</h4> ${requestScope.ex } </body>
</html>

SpringMVC系列(十三)异常处理的更多相关文章

  1. WPF MVVM UI分离之《交互与数据分离》 基础才是重中之重~delegate里的Invoke和BeginInvoke 将不确定变为确定系列~目录(“机器最能证明一切”) 爱上MVC3系列~全局异常处理与异常日志 基础才是重中之重~lock和monitor的区别 将不确定变成确定~我想监视我的对象,如果是某个值,就叫另一些方法自动运行 将不确定变成确定~LINQ DBML模型可以对

    WPF MVVM UI分离之<交互与数据分离>   在我们使用WPF过程中,不可避免并且超级喜欢使用MVVM框架. 那么,使用MVVM的出发点是视觉与业务逻辑分离,即UI与数据分离 诸如下 ...

  2. SpringBoot源码学习系列之异常处理自动配置

    SpringBoot源码学习系列之异常处理自动配置 1.源码学习 先给个SpringBoot中的异常例子,假如访问一个错误链接,让其返回404页面 在浏览器访问: 而在其它的客户端软件,比如postm ...

  3. C#进阶系列——WebApi 异常处理解决方案

    前言:上篇C#进阶系列——WebApi接口传参不再困惑:传参详解介绍了WebApi参数的传递,这篇来看看WebApi里面异常的处理.关于异常处理,作为程序员的我们肯定不陌生,记得在介绍 AOP 的时候 ...

  4. Spring Web MVC中的页面缓存支持 ——跟我学SpringMVC系列

    Spring Web MVC中的页面缓存支持 ——跟我学SpringMVC系列

  5. C#进阶系列——WebApi 异常处理解决方案(转)

    出处:http://www.cnblogs.com/landeanfen/p/5363846.html 阅读目录 一.使用异常筛选器捕获所有异常 二.HttpResponseException自定义异 ...

  6. struts2官方 中文教程 系列十三:利用通配符选择方法

    介绍 在本教程中,我们将介绍如何在struts.xml中配置action节点以达到仅使用一个action节点将几个不同的url关联到特定action类的特定方法.这样做的目的是减少struts.xml ...

  7. 爬虫系列(十三) 用selenium爬取京东商品

    这篇文章,我们将通过 selenium 模拟用户使用浏览器的行为,爬取京东商品信息,还是先放上最终的效果图: 1.网页分析 (1)初步分析 原本博主打算写一个能够爬取所有商品信息的爬虫,可是在分析过程 ...

  8. SpringMVC 三种异常处理方式

    SpringMVC 三种异常处理方式 在 SpringMVC, SpringBoot 处理 web 请求时, 若遇到错误或者异常,返回给用户一个良好的错误信息比 Whitelabel Error Pa ...

  9. SpringMVC 中的异常处理

    目录 1.搭建编码分析 2.编写异常类 3.编写自定义异常处理器 4.在springmvc.xml中配置异常处理器 5.编写Error.jsp.index.jsp页面 6.编写collector代码模 ...

随机推荐

  1. 【小白的CFD之旅】18 控制方程基础

    忙碌了一个学期终于放暑假了,小白心情很愉快.然而想起CFD教材上的那些点缀着各种让人眼花缭乱符号的数学公式,整个人就不好了.不过这些事情小白也不好意思去麻烦师兄师姐们,还得靠自己去摸索.正好趁着暑假把 ...

  2. [Windows Azure] How to Monitor Cloud Services

    How to Monitor Cloud Services To use this feature and other new Windows Azure capabilities, sign up ...

  3. linux命令(39):shell 打印偶数行,奇数行 ,行号

    awk 命令: 1. 打印行号和内容: awk '{print NR":"$0}' 2. 输出:偶数行和奇数行到文件 awk '{print $0.txt > NR%2.tx ...

  4. 第二章 使用接口(Using Interfaces)-书籍翻译

    PDF预览 下载地址 http://files.cnblogs.com/DKSoft/CodingInDelphi.pdf 1.1. 解耦(Decoupling) All through this b ...

  5. Tensorflow网址

    https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/1-1-why/ 莫烦视频学习 http://wiki.jikex ...

  6. 【C/C++】深入理解指针和数组的关系

    对数组名进行取地址运算 ,,}; ] = &a; //注意左值 对数组名取地址,得到的指针为指向整个数组的指针. 形参数组 形参为数组时勿须带数组长度,因为计算机不会处理,如果需要传数组长度, ...

  7. Lambda表达式常用代码示例

    Lambda表达式常用代码示例 2017-10-24 目录 1 Lambda表达式是什么2 Lambda表达式语法3 函数式接口是什么  3.1 常用函数式接口4 Lambdas和Streams结合使 ...

  8. [转]hive中自定义函数(UDAF)实现多行字符串拼接为一行

    函数如何使用: hive> desc concat_test;OKa       intb       string hive> select * from concat_test;OK1 ...

  9. js实现裁剪头像上传编辑器

    插件: 1.富头像上传编辑器是一款支持本地上传.预览.视频拍照和网络加载的flash头像编辑上传插件,可缩放.裁剪.旋转.定位和调色等. http://www.fullavatareditor.com ...

  10. idea linux 启动权限不足的问题

    修改 ideaproject 下所有文件  chmod -R 777 文件  递归修改文件权限