在spring 3.2中,新增了@ControllerAdvice,@RestControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。参考帮助文档。@RestControllerAdvice 是组件注解,他使得其实现类能够被classpath扫描自动发现,如果应用是通过MVC命令空间或MVC Java编程方式配置,那么该特性默认是自动开启的。
主要配合@ExceptionHandler使用,统一处理异常情况。下面的ResponseEntity、ResponseData 都是项目自定义的返回对象。
package com.cpic.chjb.web.framework.web.handler;
import com.cpic.chjb.common.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import com.cpic.chjb.common.exception.CommonException;
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public Result handlerException(RuntimeException re) {
log.info(re.getMessage(),re);
Result result = new Result();
result.setCode(500);
result.setMsg("系统运行时异常,请联系管理员!");
return result;
}
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Result handlerException(MaxUploadSizeExceededException e){
log.info(e.getMessage(),e);
Result result = new Result();
result.setCode(500);
result.setMsg("文件大小超出5MB限制, 请压缩或降低文件质量!");
return result;
}
@ExceptionHandler(CommonException.class)
public Result handlerException(CommonException ce) {
log.info(ce.getMessage(),ce);
Result result = new Result();
result.setCode(ce.getCode());
result.setMsg(ce.getMessage());
return result;
}
@ExceptionHandler(Exception.class)
public Result handlerException(Exception e) {
log.info(e.getMessage(),e);
Result result = new Result();
result.setCode(500);
result.setMsg( "系统异常");
return result;
}
}