在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。参考:@ControllerAdvice 文档
一、介绍
创建 MyControllerAdvice,并添加 @ControllerAdvice注解。
import com.jsz.service.impl.AuthenticationServiceImpl;
import com.jsz.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;/*** controller 异常捕获* @author CHENYB* @since 2017/7/17*/
@RestControllerAdvice
public class ControllerAdvice {private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServiceImpl.class);/*** 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器** @param binder*/@InitBinderpublic void initBinder(WebDataBinder binder) {}/*** 把值绑定到Model中,使全局@RequestMapping可以获取到该值* @param model*/@ModelAttributepublic void addAttributes(Model model) {}/*** 全局异常捕捉处理* @param ex* @return*/@ExceptionHandler(value = Exception.class)public JSONResult errorHandler(Exception ex) {StackTraceElement stackTraceElement = Arrays.stream(ex.getStackTrace()).findFirst().get();String fileName = stackTraceElement.getFileName();String methodName = stackTraceElement.getMethodName();int lineNumber = stackTraceElement.getLineNumber();LOGGER.error("LOCATION ------->>> {}-{}-{}, ERROR ->>> {} --------",fileName,methodName,lineNumber,ex.getMessage());return JSONResult.errorException(1000,ex.getMessage());}/*** 拦截捕捉自定义异常 MyException.class* @param ex* @return*/@ExceptionHandler(value = MyException.class)public JSONResult myErrorHandler(MyException ex) {StackTraceElement stackTraceElement = Arrays.stream(ex.getStackTrace()).findFirst().get();String fileName = stackTraceElement.getFileName();String methodName = stackTraceElement.getMethodName();int lineNumber = stackTraceElement.getLineNumber();LOGGER.error("LOCATION ------->>> {}-{}-{}, ERROR ->>> {} --------",fileName,methodName,lineNumber,ex.getMsg());return JSONResult.errorException(ex.getCode(), ex.getMsg());}
}
启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 被 @RequestMapping 注解的方法上。
@ModelAttribute:在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取,如下:
@RequestMapping("/home")
public String home(ModelMap modelMap) {System.out.println(modelMap.get("author"));
}//或者 通过@ModelAttribute获取@RequestMapping("/home")
public String home(@ModelAttribute("author") String author) {System.out.println(author);
}
@ExceptionHandler 拦截了异常,我们可以通过该注解实现自定义异常处理。其中,@ExceptionHandler 配置的 value 指定需要拦截的异常类型,上面拦截了 Exception.class 这种异常。
二、自定义异常处理(全局异常处理)
spring boot 默认情况下会映射到 /error 进行异常处理,但是提示并不十分友好,下面自定义异常处理,提供友好展示。
1、编写自定义异常类:
/*** 异常处理*/
public class MyException extends RuntimeException {public MyException(String msg) {super(msg);//封装成完整异常类this.code = 500;this.msg = msg;}private Integer code;private String msg;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}
注:spring 对于 RuntimeException 异常才会进行事务回滚。
2、编写全局异常处理类
创建 MyControllerAdvice.java,如下:
import com.jsz.service.impl.AuthenticationServiceImpl;
import com.jsz.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;/*** controller 异常捕获* @author CHENYB* @since 2017/7/17*/
@RestControllerAdvice
public class ControllerAdvice {private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServiceImpl.class);/*** 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器** @param binder*/@InitBinderpublic void initBinder(WebDataBinder binder) {}/*** 把值绑定到Model中,使全局@RequestMapping可以获取到该值* @param model*/@ModelAttributepublic void addAttributes(Model model) {}/*** 全局异常捕捉处理* @param ex* @return*/@ExceptionHandler(value = Exception.class)public JSONResult errorHandler(Exception ex) {StackTraceElement stackTraceElement = Arrays.stream(ex.getStackTrace()).findFirst().get();String fileName = stackTraceElement.getFileName();String methodName = stackTraceElement.getMethodName();int lineNumber = stackTraceElement.getLineNumber();LOGGER.error("LOCATION ------->>> {}-{}-{}, ERROR ->>> {} --------",fileName,methodName,lineNumber,ex.getMessage());return JSONResult.errorException(1000,ex.getMessage());}/*** 拦截捕捉自定义异常 MyException.class* @param ex* @return*/@ExceptionHandler(value = MyException.class)public JSONResult myErrorHandler(MyException ex) {StackTraceElement stackTraceElement = Arrays.stream(ex.getStackTrace()).findFirst().get();String fileName = stackTraceElement.getFileName();String methodName = stackTraceElement.getMethodName();int lineNumber = stackTraceElement.getLineNumber();LOGGER.error("LOCATION ------->>> {}-{}-{}, ERROR ->>> {} --------",fileName,methodName,lineNumber,ex.getMsg());return JSONResult.errorException(ex.getCode(), ex.getMsg());}
}
3、controller中抛出异常进行测试。
@RequestMapping("/home")
public String home() throws Exception {// throw new Exception("Sam 错误");throw new MyException("101", "Sam 错误");}
启动应用,访问:http://localhost:8080/home ,正常显示以下json内容,证明自定义异常已经成功被拦截。
{"msg":"Sam 错误","code":"101"}
* 如果不需要返回json数据,而要渲染某个页面模板返回给浏览器,那么MyControllerAdvice中可以这么实现:
@ExceptionHandler(value = MyException.class)
public ModelAndView myErrorHandler(MyException ex) {ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("error");modelAndView.addObject("code", ex.getCode());modelAndView.addObject("msg", ex.getMsg());return modelAndView;
}
在 templates 目录下,添加 error.ftl(这里使用freemarker) 进行渲染:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>错误页面</title>
</head>
<body><h1>${code}</h1><h1>${msg}</h1>
</body>
</html>
重启应用,http://localhost:8080/home 显示自定的错误页面内容。
自定义JSON返回封装类
public class JSONResult {// 定义jackson对象private static final ObjectMapper MAPPER = new ObjectMapper();// 响应业务状态private Integer status;// 响应消息private String msg;// 响应中的数据private Object data;@JsonIgnoreprivate String ok; // 不使用public static JSONResult build(Integer status, String msg, Object data) {return new JSONResult(status, msg, data);}public static JSONResult build(Integer status, String msg, Object data, String ok) {return new JSONResult(status, msg, data, ok);}public static JSONResult ok(Object data) {return new JSONResult(data);}public static JSONResult ok() {return new JSONResult(null);}public static JSONResult errorMsg(String msg) {return new JSONResult(500, msg, null);}public static JSONResult errorMap(Object data) {return new JSONResult(501, "error", data);}public static JSONResult errorTokenMsg(String msg) {return new JSONResult(502, msg, null);}public static JSONResult errorException(String msg) {return new JSONResult(555, msg, null);}public static JSONResult errorException(Integer status, String msg) {return new JSONResult(status, msg, null);}public static JSONResult errorUserQQ(String msg) {return new JSONResult(556, msg, null);}public JSONResult() {}public JSONResult(Integer status, String msg, Object data) {this.status = status;this.msg = msg;this.data = data;}public JSONResult(Integer status, String msg, Object data, String ok) {this.status = status;this.msg = msg;this.data = data;this.ok = ok;}public JSONResult(Object data) {this.status = 200;this.msg = "OK";this.data = data;}public Boolean isOK() {return this.status == 200;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public String getOk() {return ok;}public void setOk(String ok) {this.ok = ok;}}