1.全局异常处理类别实现异常捕获GlobalExceptionHandler
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* sql异常
*
* @param e
* @return
*/
@ExceptionHandler(BadSqlGrammarException.class)
public AjaxResult badSqlException(BadSqlGrammarException e) {
log.error("异常信息:{}", e);
return AjaxResult.fail(GlobalErrorEnum.BAD_SQL, e.getMessage());
}
/**
* 自定义异常统一捕获
*
* @param e
* @return
*/
@ExceptionHandler(RuntimeException.class)
public AjaxResult runtimeException(RuntimeException e) {
log.error("异常信息:{}", e);
int code = GlobalErrorEnum.RUN_TIME_ERROR.getCode();
try {
Method method = e.getClass().getMethod("getCode");
code = (int) method.invoke(e, new Object[]{});
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
return AjaxResult.fail(code, e.getMessage());
}
/**
* 其他异常
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public AjaxResult customException(Exception e) {
log.error("异常信息:{}", e);
if (e instanceof NullPointerException) {
return AjaxResult.fail(GlobalErrorEnum.PARAMETER_NOT_NULL.getCode(), GlobalErrorEnum.PARAMETER_NOT_NULL.getMsg(), stackTrace(e));
} else if (e instanceof OauthException) {
return AjaxResult.fail(((OauthException) e).getCode(), ((OauthException) e).getMessage(), stackTrace(e));
} else if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
List<ObjectError> errorsList = exception.getBindingResult().getAllErrors();
StringJoiner sj = new StringJoiner(";");
for (ObjectError error : errorsList) {
sj.add(error.getDefaultMessage());
}
return AjaxResult.fail(GlobalErrorEnum.PARAMETER_NOTVALID_EXCEPTION.getCode(), sj.toString(), stackTrace(e));
}
return AjaxResult.fail(GlobalErrorEnum.SYS_ERROR.getCode(), GlobalErrorEnum.SYS_ERROR.getMsg(), stackTrace(e));
}
private String stackTrace(Throwable throwable) {
if (throwable == null || throwable.getStackTrace() == null) {
return null;
}
StackTraceElement stackTraceElement = throwable.getStackTrace()[0];
return stackTraceElement.getClassName() + ":" + stackTraceElement.getLineNumber();
}
}
2.创建自定义异常,示例如下
2.1 定义自定义异常,并继承RuntimeException,必须要定义code字段
@Data
public class BusinessException extends RuntimeException {
private int code;
public BusinessException(IErrorCode errorCode) {
super(errorCode.msg());
this.code = errorCode.code();
}
}
2.2 定义异常枚举
@Getter
public enum GlobalErrorEnum implements IErrorCode {
SYS_ERROR(1001, "系统异常!!"),
LACK_OF_PARAMETER(1002, "缺少参数异常!!"),
PARAMETER_NOT_NULL(1003, "参数不能为空异常!!"),
BAD_SQL(1027, "sql语法错误!!"),
;
private int code;
private String msg;
GlobalErrorEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public int code() {
return code;
}
@Override
public String msg() {
return msg;
}
}