1. 异常处理的思路
在java中,对于异常的处理一般有两种方式:
一种在当前方法捕获处理( try-catch ),这种处理方式会造成业务代码和异常处理代码的耦合。 另一种是自己不处理,而是抛给调用者处理( throws ),调用者在抛给它的调用者,也就是往上抛。这种方法的基础上,衍生除了SpringMVC的异常处理机制。系统的 dao 、 service 、 controller 出现都通过 throws Exception 向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
2. 自定义异常处理器
步骤分析:
1.创建异常处理器类实现 handlerExceptionResolver
2.配置异常处理器
3.编写异常页面
4.测试异常跳转
(1)创建异常处理器类实现handlerExceptionResolver
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class GlobalExeceptionResovler implements HandlerExceptionResolver { /** * * @param httpServletRequest * @param httpServletResponse * @param o:对应的处理器 * @param e;实际抛出的异常对象 * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView model = new ModelAndView(); //具体的异常处理 产生异常后,跳转到一个最终的异常页面 model.addObject( "error" ,e.getMessage()); //得到错误信息 model.setViewName( "error" ); return model; } } |
(2)在Spring的配置文件配置异常处理器
1 2 3 |
<!-- 定义错误异常页面--> < bean id = "globalExecptionResovler" class = "com.weihong.excption.GlobalExeceptionResovler" />
|
(3)编写异常页面
1 2 3 4 5 6 7 8 9 |
< html > < head > < title >Title</ title > </ head > < body > < h2 >这是一个错误页面</ h2 > < h5 >错误信息为:${error}</ h5 > </ body > </ html > |
(4)测试异常跳转
1 2 3 4 5 |
@RequestMapping ( "/jumpErrorPage" ) public String jumpErrorPage(){ int res = 10 / 0 ; return "success" ; } |
( 5)测试结果
3. web的处理异常机制
当请求状态为404或者500,指定页面跳转。 在其web.xml配置如下:
1 2 3 4 5 6 7 8 9 10 |
<!--处理500异常--> < error-page > < error-code >500</ error-code > < location >/500.jsp</ location > </ error-page > <!--处理404异常--> < error-page > < error-code >404</ error-code > < location >/404.jsp</ location > </ error-page > |
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
原文链接:https://blog.csdn.net/qq_41239465/article/details/123473986
查看更多关于Java SpringMVC的自定义异常类的详细内容...