依赖spring3.2提供的新注解@ControllerAdvice,从名字上可以看出大体意思是控制器增强。原理是使用AOP对Controller控制器进行增强(前置增强、后置增强、环绕增强,AOP原理请自行查阅);那么我们可以自行对控制器的方法进行调用前(前置增强)和调用后(后置增强)的处理。
参考地址: springmvc 通过异常增强返回给客户端统一格式 - nosqlcoco - 博客园
自己项目中使用的例子(最简单使用,后期优化):
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
public Map exceptionHandler(HttpServletRequest request, Exception e) {
String message;
if(e instanceof TypeMismatchException){// 参数类型不匹配异常
TypeMismatchException ex = (TypeMismatchException) e;
message = String.format("参数类型不匹配,类型应该为: %s", ex.getRequiredType());
log.info("异常接口{} 异常信息{}",request.getRequestURI(), message);
return ResultGenerator.genHandleResult(Constant.FAIL, message);
}else if(e instanceof MissingServletRequestParameterException){// 缺少参数异常
MissingServletRequestParameterException ex = (MissingServletRequestParameterException) e;
message = String.format("缺少参数: %s", ex.getParameterName());
log.info("异常接口{} 异常信息{}", request.getRequestURI(), message);
return ResultGenerator.genHandleResult(Constant.FAIL, message);
}else if(e instanceof HttpRequestMethodNotSupportedException){// 请求类型异常
HttpRequestMethodNotSupportedException ex = (HttpRequestMethodNotSupportedException) e;
message = String.format("接口请求类型应该为: %s", ex.getSupportedHttpMethods());
log.info("接口 【{}】 请求类型错误!", request.getMethod());
return ResultGenerator.genHandleResult(Constant.FAIL, message);
}else{
log.info("异常接口{} 异常信息{}", request.getRequestURI(), e.toString());
return ResultGenerator.genHandleResult(Constant.FAIL, "服务器内部错误,请联系管理员!");
}
}
}
网友评论