咱们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者经过捕获异常从而获取异常信息,后者主要经过规范代码开发、测试经过手段减小运行时异常的发生。在开发中,不论是dao层、service层仍是controller层,都有可能抛出异常,在springmvc中,能将全部类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。这篇博文主要总结一下SpringMVC中如何统一处理异常。html
1. 异常处理思路
首先来看一下在springmvc中,异常处理的思路(我已尽力画好看点了,不要喷我~):
如上图所示,系统的dao、service、controller出现异常都经过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。明白了springmvc中的异常处理机制,下面就开始分析springmvc中的异常处理。前端
2. springmvc中自带的简单异常处理器
springmvc中自带了一个异常处理器叫SimpleMappingExceptionResolver,该处理器实现了HandlerExceptionResolver 接口,全局异常处理器都须要实现该接口。咱们要使用这个自带的异常处理器,首先得在springmvc.xml文件中配置该处理器:java
<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义默认的异常处理页面 -->
<property name="defaultErrorView" value="/WEB-INF/jsp/error.jsp"/>
<!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
<property name="exceptionAttribute" value="ex"/>
<!-- 定义须要特殊处理的异常,这是重要点 -->
<property name="exceptionMappings">
<props>
<prop key="ssm.exception.CustomException">/WEB-INF/jsp/custom_error.jsp</prop>
</props>
<!-- 还能够定义其余的自定义异常 -->
</property>
</bean>
从上面的配置来看,最重要的是要配置特殊处理的异常,这些异常通常都是咱们自定义的,根据实际状况来自定义的异常,而后也会跳转到不一样的错误显示页面显示不一样的错误信息。这里就用一个自定义异常CustomException来讲明问题,定义以下:web
//定义一个简单的异常类
public class CustomException extends Exception {
//异常信息
public String message;
public CustomException(String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
接下来就是写测试程序了,仍是使用查询的例子,以下:
而后咱们在前台输入url来测试:http://localhost:8080/SpringMVC_Study/editItems.action?id=11,故意传一个id为11,个人数据库中没有id为11的项,因此确定查不到,反正让它查不到便可。这样它就会抛出自定义的异常,而后被上面配置的全局异常处理器捕获并执行,跳转到咱们指定的页面,而后显示一下该商品不存在便可。因此这个流程是很清晰的。
从上面的过程可知,使用SimpleMappingExceptionResolver进行异常处理,具备集成简单、有良好的扩展性(能够任意增长自定义的异常和异常显示页面)、对已有代码没有入侵性等优势,但该方法仅能获取到异常信息,若在出现异常时,对须要获取除异常之外的数据的状况不适用。spring
3. 自定义全局异常处理器
全局异常处理器处理思路:数据库
- 解析出异常类型
- 若是该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展现
- 若是该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
springmvc提供一个HandlerExceptionResolver接口,自定义全局异常处理器必需要实现这个接口,以下:express
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ex.printStackTrace();
CustomException customException = null;
//若是抛出的是系统自定义的异常则直接转换
if(ex instanceof CustomException) {
customException = (CustomException) ex;
} else {
//若是抛出的不是系统自定义的异常则从新构造一个未知错误异常
//这里我就也有CustomException省事了,实际中应该要再定义一个新的异常
customException = new CustomException("系统未知错误");
}
//向前台返回错误信息
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", customException.getMessage());
modelAndView.setViewName("/WEB-INF/jsp/error.jsp");
return modelAndView;
}
}
全局异常处理器中的逻辑很清楚,我就再也不多说了,而后就是在springmvc.xml中配置这个自定义的异常处理器:json
<!-- 自定义的全局异常处理器
只要实现HandlerExceptionResolver接口就是全局异常处理器-->
<bean class="ssm.exception.CustomExceptionResolver"></bean>
而后就可使用上面那个测试用例再次测试了。能够看出在自定义的异常处理器中能获取致使出现异常的对象,有利于提供更详细的异常处理信息。通常用这种自定义的全局异常处理器比较多。mvc
4. @ExceptionHandler注解实现异常处理
还有一种是使用注解的方法,我大概说一下思路,由于这种方法对代码的入侵性比较大,我不太喜欢用这种方法。
首先写个BaseController类,并在类中使用@ExceptionHandler注解声明异常处理的方法,如:app
public class BaseController {
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
//异常处理
//......
}
}
而后将全部须要异常处理的Controller都继承这个BaseController,虽然从执行来看,不须要配置什么东西,可是代码有侵入性,须要异常处理的Controller都要继承它才行。
关于springmvc的异常处理,就总结这么多吧。
正文
Spring 统一异常处理有 3 种方式,分别为:
- 使用 @ ExceptionHandler 注解
- 实现 HandlerExceptionResolver 接口
- 使用 @controlleradvice 注解
使用 @ ExceptionHandler 注解
使用该注解有一个很差的地方就是:进行异常处理的方法必须与出错的方法在同一个Controller里面。使用以下:
1 @Controller
2 public class GlobalController {
3
4 /**
5 * 用于处理异常的
6 * @return
7 */
8 @ExceptionHandler({MyException.class})
9 public String exception(MyException e) {
10 System.out.println(e.getMessage());
11 e.printStackTrace();
12 return "exception";
13 }
14
15 @RequestMapping("test")
16 public void test() {
17 throw new MyException("出错了!");
18 }
19 }
能够看到,这种方式最大的缺陷就是不能全局控制异常。每一个类都要写一遍。
实现 HandlerExceptionResolver 接口
这种方式能够进行全局的异常控制。例如:
1 @Component
2 public class ExceptionTest implements HandlerExceptionResolver{
3
4 /**
5 * TODO 简单描述该方法的实现功能(可选).
6 * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
7 */
8 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
9 Exception ex) {
10 System.out.println("This is exception handler method!");
11 return null;
12 }
13 }
使用 @ControllerAdvice+ @ ExceptionHandler 注解
上文说到 @ ExceptionHandler 须要进行异常处理的方法必须与出错的方法在同一个Controller里面。那么当代码加入了 @ControllerAdvice,则不须要必须在同一个 controller 中了。这也是 Spring 3.2 带来的新特性。从名字上能够看出大致意思是控制器加强。 也就是说,@controlleradvice + @ ExceptionHandler 也能够实现全局的异常捕捉。
请确保此WebExceptionHandle 类能被扫描到并装载进 Spring 容器中。
1 @ControllerAdvice
2 @ResponseBody
3 public class WebExceptionHandle {
4 private static Logger logger = LoggerFactory.getLogger(WebExceptionHandle.class);
5 /**
6 * 400 - Bad Request
7 */
8 @ResponseStatus(HttpStatus.BAD_REQUEST)
9 @ExceptionHandler(HttpMessageNotReadableException.class)
10 public ServiceResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
11 logger.error("参数解析失败", e);
12 return ServiceResponseHandle.failed("could_not_read_json");
13 }
14
15 /**
16 * 405 - Method Not Allowed
17 */
18 @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
19 @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
20 public ServiceResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
21 logger.error("不支持当前请求方法", e);
22 return ServiceResponseHandle.failed("request_method_not_supported");
23 }
24
25 /**
26 * 415 - Unsupported Media Type
27 */
28 @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
29 @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
30 public ServiceResponse handleHttpMediaTypeNotSupportedException(Exception e) {
31 logger.error("不支持当前媒体类型", e);
32 return ServiceResponseHandle.failed("content_type_not_supported");
33 }
34
35 /**
36 * 500 - Internal Server Error
37 */
38 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
39 @ExceptionHandler(Exception.class)
40 public ServiceResponse handleException(Exception e) {
41 if (e instanceof BusinessException){
42 return ServiceResponseHandle.failed("BUSINESS_ERROR", e.getMessage());
43 }
44
45 logger.error("服务运行异常", e);
46 e.printStackTrace();
47 return ServiceResponseHandle.failed("server_error");
48 }
49 }
若是 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为参数列表中的异常类型。因此还能够写成这样:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler()
@ResponseBody
String handleException(Exception e){
return "Exception Deal! " + e.getMessage();
}
}
参数对象就是 Controller 层抛出的异常对象!
继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,而且能够返回自定义格式:
1 @Slf4j
2 @ControllerAdvice
3 public class ExceptionHandlerBean extends ResponseEntityExceptionHandler {
4
5 /**
6 * 数据找不到异常
7 * @param ex
8 * @param request
9 * @return
10 * @throws IOException
11 */
12 @ExceptionHandler({DataNotFoundException.class})
13 public ResponseEntity<Object> handleDataNotFoundException(RuntimeException ex, WebRequest request) throws IOException {
14 return getResponseEntity(ex,request,ReturnStatusCode.DataNotFoundException);
15 }
16
17 /**
18 * 根据各类异常构建 ResponseEntity 实体. 服务于以上各类异常
19 * @param ex
20 * @param request
21 * @param specificException
22 * @return
23 */
24 private ResponseEntity<Object> getResponseEntity(RuntimeException ex, WebRequest request, ReturnStatusCode specificException) {
25
26 ReturnTemplate returnTemplate = new ReturnTemplate();
27 returnTemplate.setStatusCode(specificException);
28 returnTemplate.setErrorMsg(ex.getMessage());
29
30 return handleExceptionInternal(ex, returnTemplate,
31 new HttpHeaders(), HttpStatus.OK, request);
32 }
33
34 }
以上就是 Spring 处理程序统一异常的三种方式。
3 @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
零、前言
对于与数据库相关的 Spring MVC 项目,咱们一般会把 事务 配置在 Service层,当数据库操做失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚。
如此一来,咱们的 Controller 层就不得不进行 try-catch Service 层的异常,不然会返回一些不友好的错误信息到客户端。可是,Controller 层每一个方法体都写一些模板化的 try-catch 的代码,很难看也难维护,特别是还须要对 Service 层的不一样异常进行不一样处理的时候。例如如下 Controller 方法代码(很是难看且冗余):
/**
* 手动处理 Service 层异常和数据校验异常的示例
* @param dog
* @param errors
* @return
*/
@PostMapping(value = "")
AppResponse add(@Validated(Add.class) @RequestBody Dog dog, Errors errors){
AppResponse resp = new AppResponse();
try {
// 数据校验
BSUtil.controllerValidate(errors);
// 执行业务
Dog newDog = dogService.save(dog);
// 返回数据
resp.setData(newDog);
}catch (BusinessException e){
LOGGER.error(e.getMessage(), e);
resp.setFail(e.getMessage());
}catch (Exception e){
LOGGER.error(e.getMessage(), e);
resp.setFail("操做失败!");
}
return resp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,只要设计得当,就不再用在 Controller 层进行 try-catch 了!并且,@Validated 校验器注解的异常,也能够一块儿处理,无需手动判断绑定校验结果 BindingResult/Errors 了!
1、优缺点
优势:将 Controller 层的异常和数据校验的异常进行统一处理,减小模板代码,减小编码量,提高扩展性和可维护性。
缺点:只能处理 Controller 层未捕获(往外抛)的异常,对于 Interceptor(拦截器)层的异常,Spring 框架层的异常,就无能为力了。
2、基本使用示例
2.1 @ControllerAdvice 注解定义全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {
}
1
2
3
请确保此 GlobalExceptionHandler 类能被扫描到并装载进 Spring 容器中。
2.2 @ExceptionHandler 注解声明异常处理方法
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
String handleException(){
return "Exception Deal!";
}
}
1
2
3
4
5
6
7
8
9
方法 handleException() 就会处理全部 Controller 层抛出的 Exception 及其子类的异常,这是最基本的用法了。
被 @ExceptionHandler 注解的方法的参数列表里,还能够声明不少种类型的参数,详见文档。其原型以下:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
/**
* Exceptions handled by the annotated method. If empty, will default to any
* exceptions listed in the method argument list.
*/
Class<? extends Throwable>[] value() default {};
}
1
2
3
4
5
6
7
8
9
10
11
12
若是 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为参数列表中的异常类型。因此上面的写法,还能够写成这样:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler()
@ResponseBody
String handleException(Exception e){
return "Exception Deal! " + e.getMessage();
}
}
1
2
3
4
5
6
7
8
9
参数对象就是 Controller 层抛出的异常对象!
3、处理 Service 层上抛的业务异常
有时咱们会在复杂的带有数据库事务的业务中,当出现不和预期的数据时,直接抛出封装后的业务级运行时异常,进行数据库事务回滚,并但愿该异常信息能被返回显示给用户。
3.1 代码示例
封装的业务异常类:
public class BusinessException extends RuntimeException {
public BusinessException(String message){
super(message);
}
}
1
2
3
4
5
6
Service 实现类:
@Service
public class DogService {
@Transactional
public Dog update(Dog dog){
// some database options
// 模拟狗狗新名字与其余狗狗的名字冲突
BSUtil.isTrue(false, "狗狗名字已经被使用了...");
// update database dog info
return dog;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
其中辅助工具类 BSUtil
public static void isTrue(boolean expression, String error){
if(!expression) {
throw new BusinessException(error);
}
}
1
2
3
4
5
那么,咱们应该在 GlobalExceptionHandler 类中声明该业务异常类,并进行相应的处理,而后返回给用户。更贴近真实项目的代码,应该长这样子:
/**
* Created by kinginblue on 2017/4/10.
* @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理全部不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail("操做失败!");
return response;
}
/**
* 处理全部业务异常
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Controller 层的代码,就不须要进行异常处理了:
@RestController
@RequestMapping(value = "/dogs", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public class DogController {
@Autowired
private DogService dogService;
@PatchMapping(value = "")
Dog update(@Validated(Update.class) @RequestBody Dog dog){
return dogService.update(dog);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
3.2 代码说明
Logger 进行全部的异常日志记录。
@ExceptionHandler(BusinessException.class) 声明了对 BusinessException 业务异常的处理,并获取该业务异常中的错误提示,构造后返回给客户端。
@ExceptionHandler(Exception.class) 声明了对 Exception 异常的处理,起到兜底做用,无论 Controller 层执行的代码出现了什么未能考虑到的异常,都返回统一的错误提示给客户端。
备注:以上 GlobalExceptionHandler 只是返回 Json 给客户端,更大的发挥空间须要按需求状况来作。
4、处理 Controller 数据绑定、数据校验的异常
在 Dog 类中的字段上的注解数据校验规则:
@Data
public class Dog {
@NotNull(message = "{Dog.id.non}", groups = {Update.class})
@Min(value = 1, message = "{Dog.age.lt1}", groups = {Update.class})
private Long id;
@NotBlank(message = "{Dog.name.non}", groups = {Add.class, Update.class})
private String name;
@Min(value = 1, message = "{Dog.age.lt1}", groups = {Add.class, Update.class})
private Integer age;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
说明:@NotNull、@Min、@NotBlank 这些注解的使用方法,不在本文范围内。若是不熟悉,请查找资料学习便可。
其余说明:
@Data 注解是 **Lombok** 项目的注解,可使咱们不用再在代码里手动加 getter & setter。
在 Eclipse 和 IntelliJ IDEA 中使用时,还须要安装相关插件,这个步骤自行Google/Baidu 吧!
1
2
3
4
5
Lombok 使用方法见:Java奇淫巧技之Lombok
SpringMVC 中对于 RESTFUL 的 Json 接口来讲,数据绑定和校验,是这样的:
/**
* 使用 GlobalExceptionHandler 全局处理 Controller 层异常的示例
* @param dog
* @return
*/
@PatchMapping(value = "")
AppResponse update(@Validated(Update.class) @RequestBody Dog dog){
AppResponse resp = new AppResponse();
// 执行业务
Dog newDog = dogService.update(dog);
// 返回数据
resp.setData(newDog);
return resp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用 @Validated + @RequestBody 注解实现。
当使用了 @Validated + @RequestBody 注解可是没有在绑定的数据对象后面跟上 Errors 类型的参数声明的话,Spring MVC 框架会抛出 MethodArgumentNotValidException 异常。
因此,在 GlobalExceptionHandler 中加上对 MethodArgumentNotValidException 异常的声明和处理,就能够全局处理数据校验的异常了!加完后的代码以下:
/**
* Created by kinginblue on 2017/4/10.
* @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理全部不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail("操做失败!");
return response;
}
/**
* 处理全部业务异常
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
/**
* 处理全部接口数据验证异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
AppResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return response;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
注意到了吗,全部的 Controller 层的异常的日志记录,都是在这个 GlobalExceptionHandler 中进行记录。也就是说,Controller 层也不须要在手动记录错误日志了。
5、总结
本文主要讲 @ControllerAdvice + @ExceptionHandler 组合进行的 Controller 层上抛的异常全局统一处理。
其实,被 @ExceptionHandler 注解的方法还能够声明不少参数,详见文档。
@ControllerAdvice 也还能够结合 @InitBinder、@ModelAttribute 等注解一块儿使用,应用在全部被 @RequestMapping 注解的方法上,详见搜索引擎。
6、附录本文示例代码已放到 Github。