spring3.2版本提供了新注解@controllerAdvice,意为控制器增强。配合@ExceptionHandler注解可以统一处理异常
注:需开启<mvc:annotation-drive>
@ControllerAdvice
public class DefaultExceptionHandler {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 统一异常处理
*
* @param e
* @return
*/
@ExceptionHandler(value = Throwable.class)
@ResponseBody
public HttpResponseEntity exceptionResolver(Throwable e) {
if (e instanceof UnauthorizedException) {
logger.warn("用户权限不足", e);
return new HttpResponseEntity(HttpStatus.FORBIDDEN);
} else if (e instanceof WechatAuthcException) {
return wechatAuthcExceptionHandle((WechatAuthcException) e);
} else if (e instanceof BindException) {
BindingResult bindingResult = ((BindException) e).getBindingResult();
return requestParamsExceptionHandle(bindingResult);
} else if (e instanceof MaxUploadSizeExceededException) {
return new HttpResponseEntity(HttpStatus.ERROR_PARAMS_REQUEST, "文件只支持10MB以下");
} else if (e instanceof StBusinessException) {
StBusinessException exception = (StBusinessException) e;
if (!ErrorDefintions.DEFAULT_FAULT_TYPE.equals(exception.getErrorType())) {
// 错误日志
logger.error("业务异常", e);
}
return new HttpResponseEntity(exception.getErrorCode(), exception.getMessageWithoutCode());
}
logger.error("统一异常处理", e);
return new HttpResponseEntity().failed();
}
/**
* 参数规则验证
*
* @param bindingResult
* @return
*/
public HttpResponseEntity requestParamsExceptionHandle(BindingResult bindingResult) {
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
Map<String, String> errorMsg = new HashMap<>();
for (FieldError fieldError : fieldErrors) {
errorMsg.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return new HttpResponseEntity(HttpStatus.ERROR_PARAMS_REQUEST, errorMsg);
}
}