支持国际化异常工具类(实际项目使用)

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青春1314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值