Spring全局异常,Controller增强方式( Advising Controllers)
1 //注意使用注解@ControllerAdvice作用域是全局Controller范围,即必须与抛出异常的method在同一个controller
2 //可应用到所有@RequestMapping类或方法上的@ExceptionHandler、@InitBinder、@ModelAttribute,在这里是@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(value = Throwable.class)
@ResponseBody
public Object handleException(HttpServletRequest request, HttpServletResponse response, Throwable exception) {
String ip = RequestUtil.getRemoteAddr(request);
String uri = RequestUtil.trimURI(request);
logger.error(String.format("ip地址%s,访问地址%s", ip, uri), exception);
Result result = Result.result(ResultCode.RESULT__ERROR_1);
// http请求方法异常,抛出异常信息;request绑定参数异常,抛出异常信息;servlet异常抛出
if (exception instanceof ServletException) {
result.setResultDesc(exception.getLocalizedMessage());
}
// 参数错误IllegalArgumentException
else if (exception instanceof IllegalArgumentException || exception.getCause() instanceof IllegalArgumentException) {
result.setResultCode(ResultCode.RESULT__ERROR_2);
result.setResultDesc(exception.getCause().getMessage());
}
// request body错误
else if (exception instanceof HttpMessageConversionException) {
String desc = exception.getLocalizedMessage();
if (desc != null && desc.contains(":")) {
desc = desc.substring(0, desc.indexOf(":"));
}
result.setResultDesc(desc);
}
// 方法中参数转换错误
else if (exception instanceof MethodArgumentTypeMismatchException) {
result.setResultDesc(String.format("参数%s错误", ((MethodArgumentTypeMismatchException) exception).getName()));
}
// ESB调用错误
else if (exception instanceof ESBException) {
return ESBResult.error(((ESBException) exception).getApplication(), exception.getLocalizedMessage());
}
// 参数校验错误
else if (exception instanceof BindException) {
BindException bindException = (BindException) exception;
result.setResultDesc(bindException.getFieldError().getDefaultMessage());
}
// db错误
else if (exception instanceof SQLException || exception.getCause() instanceof SQLException) {
result.setResultDesc("db错误");
}
return result;
}
}