java返回异常对象给前端的通用处理

文章讲述了在Java后端开发中,如何利用枚举(Enum)实现错误码和错误消息的统一管理,通过定义接口IErrorCode并让枚举实现该接口,可以方便地返回不同的错误状态给前端。同时,展示了BaseApiResult类的使用,用于构建标准的API响应,包括错误码、错误消息和返回数据。

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

java后端在不同情况下需要返回不一样的错误code和msg给前端,这个时候用枚举进行通用处理最合适。

public interface IErrorCode {
    int getCode();

    String getMsg();
}
public enum XXXEnum implements IErrorCode {

    error16(100001, "错误1..."),
    error17(100002, "错误2..."),
    error18(100003, "错误3..."),
    error19(100004, "错误4..."),
    error20(100005, "错误5..."),
    error21(100006, "错误6..."),
    error22(100007, "错误7...");

    private int code;

    private String msg;

    DetetionEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }
}
public enum ErrorCode implements IErrorCode {
    SUCCESS(1, "成功"),
    MYSQL_ERROR(100000, "MySQL访问错误"),
    REDIS_ERROR(100001, "Redis访问错误"),
    MONGODB_ERROR(100002, "MongoDB访问错误"),
    PARAMS_ERROR(100004, "参数校验错误"),
    ERROR(-1, "系统错误"),
    CAS_TIMEOUT(1000, "超时无应答"),
    CAS_NACK(1001, "否定应答"),
    CAS_BUSY(1002, "已有相同类型指令在执行"),
    CAS_OFFLINE(1003, "车辆已离线"),
    USERNAME_OR_PASSWORD_ERROR(2001, "用户名或密码错误"),
    ACCOUNT_EXPIRED(2002, "账号已过期"),
    ACCOUNT_DISABLED(2003, "账号被禁用"),
    ACCOUNT_LOCK(2004, "账号被锁定"),
    CLIENT_AUTHENTICATION_FAILED(2010, "客户端认证失败"),
    UNSUPPORTED_GRANT_TYPE(2011, "不支持的认证模式"),
    TOKEN_INVALID(2020, "token失效!"),
    NO_PERMISSION(2021, "无权限访问!"),
    SERVICE_UNAVAILABLE(3000, "找不到服务"),
    SERVER_EXCEPTION(9999, "服务端异常");

    private int code;
    private String msg;

    public int getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    private ErrorCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(
    ignoreUnknown = true
)
public class BaseApiResult<T> {
    private int code;
    private String errMsg;
    @JsonInclude(Include.NON_NULL)
    private Long total;
    private T body;

    public static <T> BaseApiResult<T> success(T object) {
        BaseApiResult<T> result = new BaseApiResult();
        result.setCode(ErrorCode.SUCCESS.getCode());
        result.setBody(object);
        return result;
    }

    public static <T> BaseApiResult<T> success(long total, T object) {
        BaseApiResult<T> result = new BaseApiResult();
        result.setCode(ErrorCode.SUCCESS.getCode());
        result.setBody(object);
        result.setTotal(total);
        return result;
    }

    public static <T> BaseApiResult<T> success() {
        return success((Object)null);
    }

    public static <T> BaseApiResult<T> error(BaseApiResult<?> result) {
        return error(result.getCode(), result.getErrMsg());
    }

    public static <T> BaseApiResult<T> error(IErrorCode errorCode) {
        BaseApiResult<T> result = new BaseApiResult();
        result.setCode(errorCode.getCode());
        result.setErrMsg(errorCode.getMsg());
        return result;
    }

    public static <T> BaseApiResult<T> error(IErrorCode errorCode, Object... args) {
        String msg = String.format(errorCode.getMsg(), args);
        return error(errorCode.getCode(), msg);
    }

    public static <T> BaseApiResult<T> error(String errMsg) {
        return error(-1, errMsg);
    }

    public static <T> BaseApiResult<T> error(int code, String errMsg) {
        BaseApiResult<T> result = new BaseApiResult();
        result.setCode(code);
        result.setErrMsg(errMsg);
        return result;
    }

    public static <T> BaseApiResult<T> of(int code, String errMsg, T object) {
        BaseApiResult<T> result = new BaseApiResult();
        result.setCode(code);
        result.setBody(object);
        result.setErrMsg(errMsg);
        return result;
    }

    public BaseApiResult() {
    }

    public int getCode() {
        return this.code;
    }

    public String getErrMsg() {
        return this.errMsg;
    }

    public Long getTotal() {
        return this.total;
    }

    public T getBody() {
        return this.body;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public void setBody(T body) {
        this.body = body;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof BaseApiResult)) {
            return false;
        } else {
            BaseApiResult<?> other = (BaseApiResult)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getCode() != other.getCode()) {
                return false;
            } else {
                label49: {
                    Object this$errMsg = this.getErrMsg();
                    Object other$errMsg = other.getErrMsg();
                    if (this$errMsg == null) {
                        if (other$errMsg == null) {
                            break label49;
                        }
                    } else if (this$errMsg.equals(other$errMsg)) {
                        break label49;
                    }

                    return false;
                }

                Object this$total = this.getTotal();
                Object other$total = other.getTotal();
                if (this$total == null) {
                    if (other$total != null) {
                        return false;
                    }
                } else if (!this$total.equals(other$total)) {
                    return false;
                }

                Object this$body = this.getBody();
                Object other$body = other.getBody();
                if (this$body == null) {
                    if (other$body != null) {
                        return false;
                    }
                } else if (!this$body.equals(other$body)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof BaseApiResult;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        result = result * 59 + this.getCode();
        Object $errMsg = this.getErrMsg();
        result = result * 59 + ($errMsg == null ? 43 : $errMsg.hashCode());
        Object $total = this.getTotal();
        result = result * 59 + ($total == null ? 43 : $total.hashCode());
        Object $body = this.getBody();
        result = result * 59 + ($body == null ? 43 : $body.hashCode());
        return result;
    }

    public String toString() {
        return "BaseApiResult(code=" + this.getCode() + ", errMsg=" + this.getErrMsg() + ", total=" + this.getTotal() + ", body=" + this.getBody() + ")";
    }
}
	return BaseApiResult.error(XXXEnum.error1);
### Java 中实现统一响应对象的方法 为了确保应用程序的一致性和可靠性,在Java项目中通常会定义一个通用的响应对象来封装API调用的结果。这种做法不仅提高了代码的可读性,还简化了客户端对接口的理解过程。 #### 定义统一响应对象结构 创建一个`ResponseResult<T>`泛型类作为所有HTTP请求的标准回应载体: ```java public class ResponseResult<T> { private Integer code; private String message; private T data; // 构造函数、getter 和 setter 方法省略 public static <T> ResponseResult<T> success(T data){ ResponseResult<T> result = new ResponseResult<>(); result.setCode(200); result.setMessage("成功"); result.setData(data); return result; } public static <T> ResponseResult<T> fail(Integer code, String msg){ ResponseResult<T> result = new ResponseResult<>(); result.setCode(code); result.setMessage(msg); return result; } } ``` 此设计允许开发者轻松构建成功的响应以及失败情况下的反馈信息[^2]。 #### 结合全局异常处理器使用 当遇到未预期的情况时,可以通过自定义的全局异常处理机制自动返回格式化的错误消息给前端应用。这有助于保持前后端交互的一致性,并使调试更加容易[^3]。 ```java import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseResult<String> handleException(Exception e) { // 记录日志等操作... return ResponseResult.fail(ResponseCode.SERVER_ERROR.getCode(), e.getMessage()); } } ``` 上述配置使得任何地方抛出未经捕获的异常都会触发该方法,从而返回标准化的JSON格式响应体。 #### 返回结果样例 无论是正常的数据查询还是发生异常的情况下,最终都将以相同的格式呈现给调用方: - 成功情况下: ```json {"code":200,"message":"成功","data":{"key":"value"}} ``` - 出错情形下: ```json {"code":500,"message":"服务器内部错误"} ``` 这种方法极大地增强了系统的健壮性和用户体验一致性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值