出现异常并不可怕,可怕的是出现了异常,你却不知道,也没有进行异常处理。
Spring MVC的Controller出现异常的默认处理是响应一个500状态码,再把错误信息显示在页面上,如果用户看到这样的页面,一定会觉得你这个网站太LOW了。
要解决Controller的异常问题,当然也不能在每个处理请求的方法中加上异常处理,那样太繁琐。Spring MVC提供了一个HandlerExceptionResolver接口,可用于统一异常处理。
HandlerExceptionResolver接口
- 1
- 2
- 3
HandlerExceptionResolver接口中定义了一个resolveException方法,用于处理Controller中的异常。Exception ex参数即Controller抛出的异常。返回值类型是ModelAndView,可以通过这个返回值来设置异常时显示的页面。
实现HandlerExceptionResolver
HandlerExceptionResolver是一个interface,还需要定义一个实现类,来实现异常出现后的逻辑。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
上面代码实现了HandlerExceptionResolver类的resolveException方法。出现异常时,会将异常信息存储到数据库,并显示专门的错误页面。
当然,还有一些其他常用的异常处理方法,例如通过javamail将异常报警发送给相关人员。总之,出现的异常要能被相关人员看到,这样才能不断完善代码。
配置
最后,还需要将自己的HandlerExceptionResolver实现类配置到Spring配置文件中,或者加上@Component注解。
- 1
至此,MyExceptionResolver就可以处理Controller抛出的异常了。
相关问题
HandlerExceptionResolver和web.xml中配置的error-page会有冲突吗?
web.xml中配置error-page同样是配置出现错误时显示的页面:
- 1
- 2
- 3
- 4
如果resolveException返回了ModelAndView,会优先根据返回值中的页面来显示。不过,resolveException可以返回null,此时则展示web.xml中的error-page的500状态码配置的页面。
当web.xml中有相应的error-page配置,则可以在实现resolveException方法时返回null。
API文档中对返回值的解释:
return a corresponding ModelAndView to forward to, or null for default processing.