统一异常处理:本文介绍spring MVC的自定义异常处理,即在Controller中抛出自定义的异常时,客户端收到更友好的JSON格式的提示。而不是常见的报错页面。
1. 使用@ControllerAdvice注解
@ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。使用<context:component-scan>扫描时也能扫描到。
@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。非常简单
,不过只有当使用@ExceptionHandler最有用,另外两个用处不大。
com.spirng.exception包下,建立统一异常处理le
@ControllerAdvice
public class EvaluationExceptionHandler extends ResponseEntityExceptionHandler {
protected final MediaType mediaType = new MediaType("application", "json", Charset.forName("utf-8"));
@ExceptionHandler(RuntimeException.class)
public String runtimeExcep(HttpServletRequest request, Exception ex){
return "index";
}
@ExceptionHandler(SQLException.class)
@ResponseBody
public ResponseEntity<EvaluationException> processException(HttpServletRequest req, SQLException exception){
EvaluationException ev = new EvaluationException(ErrorCode.ONE, "sql error");
return ResponseEntity.ok().contentType(mediaType).body(ev);
}
}
其中,
@ExceptionHandler(SignException.class)
即表示让Spring捕获到所有抛出的SignException异常,并交由这个被注解的方法处理。
@ResponseBody
即表示返回的对象,Spring会自动把该对象进行json转化,最后写入到Response中。
ResponseEntity<EvaluationException> 是返回给前端的一个对象,可以看成是httpResponse,包含HttpHeaders、HttpStatus、
httpBody等,其中,EvaluationException是消息体内容,由于设置了ResponseBody,前端会将其
转换为json格式显示。这里EvaluationException是Exception的子类,所以json中还会包含StackTrace。
官方介绍: ResponseEntity
2. 第一歩中,EvaluationException是自定义异常
异常类型的枚举类:
package com.spring.common.exception;
/**
* Created by lsj on 17/7/28.
*/
public enum ErrorCode {
ONE(101, "oneErrorCode"),
TWO(102, "twoErrorCode");
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private int code;
private String type;
private ErrorCode(int code, String type) {
this.code = code;
this.type = type;
}
}
package com.spring.common.exception;
/**
* Created by lsj on 17/7/28.
*/
public class EvaluationException extends RuntimeException {
private static final long serialVersionUID = 3753281873702679352L;
private ErrorCode errorCode;
public EvaluationException(ErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public EvaluationException(ErrorCode errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public void setErrorCode(ErrorCode errorCode) {
this.errorCode = errorCode;
}
}
3. dispatcher-servlet.xml中添加配置:
<context:component-scan base-package="com.spring.Controller, com.spring.common.exception"/>
相关:
http://jinnianshilongnian.iteye.com/blog/1866350
http://blog.csdn.net/cesul/article/details/38539343
。。。