@SpringBoot异常处理-@ControllerAdvice+@ExceptionHandler 注解处理异常
版权声明:本文为CSDN博主「爱吃西瓜的小松鼠」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40979622/article/details/83188701
@ControllerAdvice+@ExceptionHandler 注解处理异常
需要创建一个能够处理异常的全局异常类。在该类上需
要添加@ControllerAdvice 注解/**
如图所示:
public class CommonException extends RuntimeException {
private int errorCode;
private Class<?> errorClass;
private String errorMsg;
private String detailErrorMsg;
public CommonException(Throwable cause, int errorCode, String errorMsg) {
super(cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public CommonException(int errorCode, String errorMsg, Class<?> errorClass) {
this.errorClass = errorClass;
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public CommonException(Throwable cause, int errorCode, Class<?> errorClass, String errorMsg) {
super(cause);
this.errorCode = errorCode;
this.errorClass = errorClass;
this.errorMsg = errorMsg;
}
public CommonException(int errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public CommonException(int errorCode, Class<?> errorClass, String errorMsg) {
this.errorCode = errorCode;
this.errorClass = errorClass;
this.errorMsg = errorMsg;
}
public CommonException(int errorCode, String errorMsg, String detailErrorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.detailErrorMsg = detailErrorMsg;
}
public CommonException(int errorCode, Class<?> errorClass, String errorMsg, String detailErrorMsg) {
this.errorCode = errorCode;
this.errorClass = errorClass;
this.errorMsg = errorMsg;
this.detailErrorMsg = detailErrorMsg;
}
public CommonException(Throwable cause, int errorCode, String errorMsg, String detailErrorMsg) {
super(cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.detailErrorMsg = detailErrorMsg;
}
public CommonException(Throwable cause, int errorCode, Class<?> errorClass, String errorMsg, String detailErrorMsg) {
super(cause);
this.errorCode = errorCode;
this.errorClass = errorClass;
this.errorMsg = errorMsg;
this.detailErrorMsg = detailErrorMsg;
}
public String getMessage() {
return this.errorMsg;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public void setErrorClass(Class<?> errorClass) {
this.errorClass = errorClass;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public void setDetailErrorMsg(String detailErrorMsg) {
this.detailErrorMsg = detailErrorMsg;
}
public int getErrorCode() {
return this.errorCode;
}
public Class<?> getErrorClass() {
return this.errorClass;
}
public String getErrorMsg() {
return this.errorMsg;
}
public String getDetailErrorMsg() {
return this.detailErrorMsg;
}
}
@ResponseBody
@ControllerAdvice
public class ExceptionHandlerAdvice {
private static final Logger log = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
public ExceptionHandlerAdvice() {
log.debug("Enabled Exception Handler Advice [启动服务异常处理]");
}
@ExceptionHandler({CommonException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handleException(CommonException e) {
if (e.getErrorClass() != null) {
Logger logger = LoggerFactory.getLogger(e.getErrorClass());
logger.error(e.getMessage(), e);
} else {
log.error(e.getMessage(), e);
}
return Result.error(e.getErrorCode(), e.getErrorMsg());
}
@ExceptionHandler({MissingServletRequestParameterException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handleException(MissingServletRequestParameterException e) {
String parameterName = e.getParameterName();
String parameterType = e.getParameterType();
log.error("缺少必填参数{} {}", new Object[]{parameterType, parameterName, e});
return Result.error(100400, Translator.toLocale("RequiredParameter", "缺少必填参数:") + parameterName);
}
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result handleException(HttpRequestMethodNotSupportedException e) {
String message = e.getMessage();
log.error(message, e);
String[] split = message.split("'");
return split.length >= 2 ? Result.error(100400, String.format(Translator.toLocale("ErrorRequestMethodFmt", "请求方式错误"), split[1])) : Result.error(100400, Translator.toLocale("ErrorRequestMethod", "请求方式错误"));
}
@ExceptionHandler({Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handleException(Throwable e) {
String message = e.getMessage() != null ? e.getMessage() : e.toString();
log.error(message, e);
String regEx = "[一-龥]";
Pattern p = Pattern.compile("[一-龥]");
if (p.matcher(message).find()) {
return Result.error(100500, message);
} else if (!message.contains("timeout") && !message.contains("timedout")) {
return Result.error(100500, Translator.toLocale("ServerError", "服务器内部异常"));
} else {
return message.contains("refused") ? Result.error(100502, Translator.toLocale("ConnectionRefused", "服务器拒绝连接")) : Result.error(100504, Translator.toLocale("ConnectionTimeOut", "服务器连接超时"));
}
}
@ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handleException(Exception e) {
log.error(e.getMessage(), e);
return Result.error(100400, this.getBindMessage(e.getMessage()));
}
@ExceptionHandler({NoHandlerFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public Result noMapping(NoHandlerFoundException e) {
log.error(e.getMessage(), e);
return Result.error(100404, Translator.toLocale("PathNotFound", "请求路径不存在"));
}
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result errorParam(MethodArgumentTypeMismatchException me) {
log.error(me.getMessage(), me);
return Result.error(100400, Translator.toLocale("WrongParameter", "请求参数不合法"));
}
@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public Result handleException(HttpMediaTypeNotSupportedException e) {
String message = e.getMessage();
log.error(message, e);
String[] split = message.split("'");
return split.length >= 2 ? Result.error(100415, String.format(Translator.toLocale("TextTypeErrorFmt", "参数文本类型错误"), split[1])) : Result.error(100415, Translator.toLocale("TextTypeError", "参数文本类型错误"));
}
private String getBindMessage(String str) {
if (StringUtils.hasText(str)) {
String[] sa = str.split("message");
if (sa.length > 0) {
for(int i = sa.length - 1; i >= 0; --i) {
if (sa[i].getBytes().length != sa[i].length()) {
str = sa[i].trim().replace("[", "");
String[] st = str.split("]");
if (st.length > 0) {
str = st[0];
}
break;
}
}
}
}
return str;
}
}
public class Translator {
private static ResourceBundleMessageSource messageSource;
public Translator() {
}
public static String toLocale(String msg) {
if (StringUtils.isBlank(msg)) {
return null;
} else {
if (messageSource == null) {
try {
messageSource = (ResourceBundleMessageSource)SpringContextHolder.getBean(ResourceBundleMessageSource.class);
} catch (NoSuchBeanDefinitionException var2) {
return msg;
}
}
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(msg, (Object[])null, locale);
}
}
public static String toLocale(String code, String defaultMsg) {
String result = toLocale(code);
return result == null || defaultMsg != null && result.equals(code) ? defaultMsg : result;
}
}