Spring异常处理@ExceptionHandler
最近学习Spring时,认识到Spring异常处理的强大。之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑:
try{
..........
}catch(Exception1 e){
..........
}catch(Exception2 e){
...........
}catch(Exception3 e){
...........
}
Spring能够较好的处理这种问题,核心如下,文章主要关注前两个:
- @ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度
- @ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开;其是对Controller层进行拦截
- @ResponseStatus:可以将某种异常映射为HTTP状态码
@ExceptionHandler
源码如下:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
Class<? extends Throwable>[] value() default {};
}
该注解作用对象为方法,并且在运行时有效,value()可以指定异常类。由该注解注释的方法可以具有灵活的输入参数(详细参见Spring API):
- 异常参数:包括一般的异常或特定的异常(即自定义异常),如果注解没有指定异常类,会默认进行映射。
- 请求或响应对象 (Servlet API or Portlet API): 你可以选择不同的类型,如ServletRequest/HttpServletRequest或PortleRequest/ActionRequest/RenderRequest
。 - Session对象(Servlet API or Portlet API): HttpSession或PortletSession。
- WebRequest或NativeWebRequest
- Locale
- InputStream/Reader
- OutputStream/Writer
Model
方法返回值可以为:
- ModelAndView对象
- Model对象
- Map对象
- View对象
- String对象
- 还有@ResponseBody、HttpEntity<?>或ResponseEntity<?>,以及void
@ControllerAdvice
源码如下:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
@AliasFor("basePackages")
String[] value() default {};
@AliasFor("value")
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
Class<?>[] assignableTypes() default {};
Class<? extends Annotation>[] annotations() default {};
}
该注解作用对象为TYPE,包括类、接口和枚举等,在运行时有效,并且可以通过Spring扫描为bean组件。其可以包含由@ExceptionHandler、@InitBinder 和@ModelAttribute标注的方法,可以处理多个Controller类,这样所有控制器的异常可以在一个地方进行处理。
实例
异常类:
public class CustomGenericException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public CustomGenericException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}
控制器:
@Controller
@RequestMapping("/exception")
public class ExceptionController { @RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
if ("error".equals(type)) {
// 由handleCustomException处理
throw new CustomGenericException("E888", "This is custom message");
} else if ("io-error".equals(type)) {
// 由handleAllException处理
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
}
异常处理类:
@ControllerAdvice
public class ExceptionsHandler { @ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ //还可以声明接收其他任意参数
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errCode",exception.getErrCode());
modelAndView.addObject("errMsg",exception.getErrMsg());
return modelAndView;
} @ExceptionHandler(Exception.class)//可以直接写@EceptionHandler,IOExeption继承于Exception
public ModelAndView allExceptionHandler(Exception exception){
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errMsg", "this is Exception.class");
return modelAndView;
}
}
JSP页面:
正常页面index.jsp:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Spring MVC @ExceptionHandler Example</h2> <c:if test="${not empty msg}">
<h2>${msg}</h2>
</c:if> </body>
</html>
异常处理页面generic_error.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body> <c:if test="${not empty errCode}">
<h1>${errCode} : System Errors</h1>
</c:if> <c:if test="${empty errCode}">
<h1>System Errors</h1>
</c:if> <c:if test="${not empty errMsg}">
<h2>${errMsg}</h2>
</c:if> </body>
</html>
测试运行如下:
正常情况:

CustomGenericException异常情况:

IOException异常情况:

总结
- @ExceptionHandler和@ControllerAdvice能够集中异常,使异常处理与业务逻辑分离
- 本文重点理解两种注解方式的使用
参考:
- Spring API:http://docs.spring.io/spring/docs/current/javadoc-api/
- 《Spring in Action》
- Spring MVC @ExceptionHandler Example
Spring异常处理@ExceptionHandler的更多相关文章
- Spring 异常处理三种方式 @ExceptionHandler
异常处理方式一. @ExceptionHandler 异常处理方式二. 实现HandlerExceptionResolver接口 异常处理方式三. @ControllerAdvice+@Excepti ...
- spring异常处理
http://cgs1999.iteye.com/blog/1547197 1 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到 ...
- Unit06: Spring对JDBC的 整合支持 、 Spring+JDBC Template、Spring异常处理
Unit06: Spring对JDBC的 整合支持 . Spring+JDBC Template .Spring异常处理 1. springmvc提供的异常处理机制 我们可以将异常抛给spring框架 ...
- Spring的@ExceptionHandler和@ControllerAdvice统一处理异常
之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch try{ ..........}catch(Exception1 e){ ......... ...
- Spring MVC 异常处理 - ExceptionHandler
通过HandlerExceptionResolver 处理程序异常,包括Handler映射, 数据绑定, 以及目标方法执行时的发生的异常 实现类如下 /** * 1. 在 @ExceptionHand ...
- 统一异常处理@ExceptionHandler
异常处理功能中用到的注解是:@ExceptionHandler(异常类型.class). 这个注解的功能是:自动捕获controller层出现的指定类型异常,并对该异常进行相应的异常处理. 比如我要在 ...
- Spring @ControllerAdvice @ExceptionHandler 全局处理异常
对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...
- spring 异常处理的方式?
一.使用SimpleMappingExceptionResolver解析器 1.1在mvc中进行 配置. <?xml version="1.0" encoding=" ...
- Spring @ControllerAdvice @ExceptionHandler
先来两个连接: Spring3.2新注解@ControllerAdvice Spring 注解学习手札(八)补遗——@ExceptionHandler @Controller Class中如果有@Ex ...
随机推荐
- PHP curl_setopt函数用法介绍
[导读] curl_setopt函数是php中一个重要的函数,它可以模仿用户的一些行为,如模仿用户登录,注册等等一些用户可操作的行为哦.bool curl_setopt (int ch, string ...
- 我这样减少了26.5M Java内存!
WeTest 导读 历时五天的内存优化已经结束,这里总结一下这几天都做了什么,有哪些收获.优化了,或可以优化的地方都有哪些.(因为很多事还没做,有些结论需要一定样本量才能断定,所以叫一期)一期优化减少 ...
- ListView原理
表明转载自http://blog.csdn.net/iispring/article/details/50967445 在自己定义Adapter时,我们经常会重写Adapter的getView方法,该 ...
- 阿里云部署Docker(6)----解决删除<none>镜像问题
转载请注明来源,本博客原创作者为:http://blog.csdn.net/minimicall?viewmode=contents 在Docker使用中,常常会碰到删除镜像不成功.反而让镜像变成了& ...
- 一起读源码之zookeeper(1) -- 启动分析
从本文开始,不定期分析一个开源项目源代码,起篇从大名鼎鼎的zookeeper开始. 为什么是zk,因为用到zk的场景实在太多了,大部分耳熟能详的分布式系统都有zookeeper的影子,比如hbase, ...
- MPSOC之2——ubuntu环境配置及petalinux安装
MPSOC的linux开发需要使用petalinux,选择Ubuntu操作系统. 1.Ubuntu 1.1. Ubuntu安装 版本16.04.03 vmare版本:12.0 安装时注意选择" ...
- mysql千万级数据表,创建表及字段扩展的几条建议
一:概述 当我们设计一个系统时,需要考虑到系统的运行一段时间后,表里数据量大约有多少,如果在初期,就能估算到某几张表数据量非常庞大时(比如聊天消息表),就要把表创建好,这篇文章从创建表,增加数据,以及 ...
- 深入理解计算机系统_3e 第七章家庭作业 CS:APP3e chapter 7 homework
7.6 +-----------------------------------------------------------------------+ |Symbol entry? Symbol ...
- redis的事务(简单介绍)
1.简单描述 redis对事务的支持目前还是比较简单.redis只能保证一个client发起的事务中的命令是可以连续的执行,而中间不会插入其他client的命令.由于redis是但现场来处理所有cli ...
- dedecms在php7下的使用方法,织梦dedecsm后台一片空白的解决方法
前几天,一个老客户,最近升级了服务器,php到php7,把织梦dedecms转移到新服务器后,不能登录后台,让帮忙看一下. 我看了下他们的网站,使用的是织梦V57_UTF8_SP1前台页面是可以访问的 ...