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);
}
}
本文介绍了一个基于Java的异常处理框架的设计与实现。该框架通过定义通用的错误码接口及异常基类,支持国际化消息和灵活的错误信息定制。具体包括pom依赖配置、错误码接口定义、抽象基础异常类及业务异常类的具体实现。

被折叠的 条评论
为什么被折叠?



