1、pom依赖 <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>3.0.2</version> </dependency> 2、ErrorCode 接口
import org.apache.commons.lang3.StringUtils; public interface ErrorCode { String getCode(); default String getMessage (){ return StringUtils.EMPTY; } default int getHttpStatus() { return 500; } }
3、抽象基础异常类:BaseException
import javax.annotation.Nullable; public abstract class BaseException extends RuntimeException{ protected static final long serialVersionUID = 1L; private transient ErrorCode errorCode; private transient Object[] messageArgs; public ErrorCode getErrorCode() { return errorCode; } public Object[] getMessageArgs() { return messageArgs; } public boolean isI18nEnable() { return true; } protected BaseException(String message) { super(message); } protected BaseException(String message, Throwable cause) { super(message, cause); } protected BaseException(ErrorCode errorCode) { this(errorCode, new Object[0]); } protected BaseException(ErrorCode errorCode, @Nullable Object ... messageArgs) { this(errorCode, null, messageArgs); } protected BaseException(ErrorCode errorCode, @Nullable Throwable cause, @Nullable Object ... messageArgs) { super(errorCode.getCode(), cause); this.errorCode = errorCode; this.messageArgs = messageArgs; } }
4、业务异常类:BusinessException
import javax.annotation.Nullable; /** * 参数校验异常 * */ public class BusinessException extends BaseException{ public BusinessException(String message) { super(message); } public BusinessException(String message, Throwable cause) { super(message, cause); } public BusinessException(ErrorCode errorCode) { super(errorCode); } public BusinessException(ErrorCode errorCode, @Nullable Object... messageArgs) { super(errorCode, messageArgs); } public BusinessException(ErrorCode errorCode, @Nullable Throwable cause, @Nullable Object... messageArgs) { super(errorCode, cause, messageArgs); } }