介绍
@RestControllerAdvice/@ControllerAdvice是@Component的强化版,是spring mvc提供的功能,在spring boot可以直接使用。
使用该注解的类可以拥有@ExceptionHandler, @InitBinder或 @ModelAttribute注解的方法,并且这些方法会被应用到控制器类层次的所有的@RequestMapping方法上。
@ExceptionHandler注解表明出现它绑定的异常时调用该方法进行异常处理,例如:IOException, SQLException等等。
@InitBinder注解初始化数据绑定的
使用场景
全局异常处理
全局数据绑定
全局数据预处理
创建RestControllerAdvice/ControllerAdvice处理类
@ControllerAdvice
// or use @RestControllerAdvice
@Slf4j
public class CommonControllerAdvice{
/**
* 应用到所有@RequestMapping注解方法,
* 在执行之前进行初始化数据绑定
* @param binder
*/
public void initBinder(WebDataBinder binder){//WebDataBinder是对表单到方法的绑定
binder.getFieldDefaultPrefix();
binder.getDieldMarkerPrefix();
//数据初始化绑定
}
/**
* 把值绑定到Model中
* 使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "lz");
}
/**
* 全局异常捕捉处理
*/
@ExceptionHandler(RRException.class)
public Response apiExceptionHandler(UnionException e) {
return Response .fail(e);
}
/**
* 如果出现了IO异常,进入该方法进行处理
*
* @param exception
* @param response
* @return
*/
@ExceptionHandler(IOException.class)
public Response handleIOException(IOException exception, HttpServletResponse response) {
log.error("IO异常", exception);
Throwable throwable = exception;
if (exception instanceof FileNotFoundException) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
// 主要解决链式异常的消息提取问题,默认提取触发异常的最原始异常的消息
while (throwable.getCause() != null) {
throwable = throwable.getCause();
}
}
return Response.genResult(Response.RESP_CODE_FAIL, throwable);
}
/**
* 如果数据库发生了异常(违反唯一约束,未找到父项关键字,数据库连接异常等),则由该
* 异常处理器处理。该方法会对本次响应设置500响应状态码,并在message中返回异常的详细信息
*
* @param exception
* @param response
* @return
*/
@ExceptionHandler(SQLException.class)
public Response handleSQLIntegrityException(SQLException exception, HttpServletResponse response) {
log.error("SQL异常", exception);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
Throwable throwable = exception;
while (throwable.getCause() != null) {
throwable = throwable.getCause();
}
return Response.genResult(Response.RESP_CODE_FAIL, exception);
}
}
创建CommonException类
public class CommonException extends RuntimeException {
private String message;
public CommonException() {
super();
this.message= message;
}
public CommonException(String message,Throwable cause) {
super(message);
this.message= message;
}
public CommonException(String message) {
super(message);
this.message= message;
}
public CommonException(Throwable cause) {
super(cause);
this.message= message;
}
}