异常处理机制流程图
系统中异常包括两类:
预期异常 | 通过捕获异常从而获取异常信息。 |
运行时异常RuntimeException | 主要通过规范代码开发、测试等手段减少运行时异常的发生。 |
系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后SpringMVC前端控制器交由异常处理器进行异常处理,如下图:
异常处理的两种方式
- 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver。这种方式简单快捷,使用方便。
- 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器。这种方式可根据具体的项目需求,提示对应的异常信息。
简单异常处理器SimpleMappingExceptionResolver
1
2
3
4
5
6
7
8
9
10
|
< bean class=“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”> < property name=“defaultErrorView” value=“error”/> <!-- 默认错误视图--> < property name=“exceptionMappings”> < map > <!--异常类型 错误视图--> < entry key = "com.project.exception.MyException" value = "error" /> < entry key = "java.lang.ClassCastException" value = "error" /> </ map > </ property > </ bean > |
自定义异常处理步骤
① 创建异常处理器类实现HandlerExceptionResolver
1
2
3
4
5
6
7
8
9
10
|
public class MyExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //处理异常的代码实现 //创建ModelAndView对象 ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName( "exceptionPage" ); return modelAndView; } } |
② 配置异常处理器
1
2
|
< bean id = "exceptionResolver" class = "com.project.exception.MyExceptionResolver" /> |
③ 编写异常页面
1
2
3
4
5
6
7
8
9
|
<%@ page contentType="text/html;charset=UTF-8" language="java" %> < html > < head > < title >自定义异常界面</ title > </ head > < body > 自定义异常提示信息 </ body > </ html > |
④ 测试异常跳转
1
2
3
4
5
6
|
@RequestMapping ( "/quick" ) @ResponseBody public void quickMethod22() throws IOException, ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd" ); simpleDateFormat.parse( "123456" ); } |
本章小结
异常处理方式
- 配置简单异常处理器SimpleMappingExceptionResolver
- 自定义异常处理器
自定义异常处理步骤
① 创建异常处理器类实现HandlerExceptionResolver
② 配置异常处理器
③ 编写异常页面
④ 测试异常跳转
到此这篇关于Java 超详细讲解Spring MVC异常处理机制的文章就介绍到这了,更多相关Java Spring MVC 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_52360069/article/details/123938121