自定义异常
/**
* @author dai
* @date 2022/10/11
*/
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final ErrorCode errorCode;
public CustomException(ErrorCode errorCode) {
super(errorCode.message());
this.errorCode = errorCode;
}
public CustomException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}
public CustomException(Throwable cause, ErrorCode errorCode) {
super(errorCode.message(), cause);
this.errorCode = errorCode;
}
public CustomException(String message, Throwable cause, ErrorCode errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, ErrorCode errorCode) {
super(message, cause, enableSuppression, writableStackTrace);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
全局异常处理
/**
* @author dai
* @date 2022/10/11
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = CustomException.class)
public Result<Void> handle(CustomException e) {
return Result.failed(e.getErrorCode());
}
}