Fork me on Gitee

定义通用返回包装类

定义通用返回包装类

包装返回正确的数据格式,返回类型示例

{
  "code":200,
  "message":"success",
  "data":[
    
  ]
}

通用包装类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author zhangshao
 * @description 通用响应类
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CommonResponse {
    /**
     * 状态码
     */
    private int code;
    /**
     * 对应请求的返回处理结果, 如:成功、失败等
     */
    private String message;

    private Object data;

    public static CommonResponse ok(){
        return CommonResponse.ok(null);
    }
    public static CommonResponse ok(Object result){
        return CommonResponse.ok("success",result);
    }

    public static CommonResponse ok(String status,Object result){
        CommonResponse response = new CommonResponse();
        response.setCode(200);
        response.setMessage(status);
        response.setData(result);
        return response;
    }

    public static CommonResponse error(String status){
        CommonResponse response = new CommonResponse();
        response.setCode(500);
        response.setMessage(status);
        return response;
    }
    public static CommonResponse error(CommonError commonError){
        CommonResponse response = new CommonResponse();
        response.setCode(commonError.getErrCode());
        response.setMessage(commonError.getErrMsg());
        return response;
    }

    public static CommonResponse error(int code,String status){
        CommonResponse response = new CommonResponse();
        response.setCode(code);
        response.setMessage(status);
        return response;
    }



}

其中CommonError为抽象类

public interface CommonError {
    public int getErrCode();
    public String getErrMsg();

    public CommonError setErrMsg(String errMsg);


}

image-20241231112627997

使用BusinessEnum实现该抽象类,使用BusinessErrorEnum定义业务异常

import lombok.AllArgsConstructor;

@AllArgsConstructor
public enum BusinessErrorEnum implements CommonError{
    // 通用错误类型10001
    PARAMETER_VALIDATION_ERROR(10001,"参数校验错误"),

    UNKNOWN_ERROR(10002,"未知错误"),

    // 20000开头为用户信息相关错误定义
    USER_NOT_EXIST(20001,"用户不存在"),

    // 30001开头为svn相关错误定义
    ADD_SVN_REPO_ERROR(30001,"添加SVN仓库失败"),
    DEL_SVN_REPO_ERROR(30002,"删除SVN仓库失败"),

    BATCH_DEL_SVN_REPO_ERROR(30003,"批量删除SVN仓库失败"),


    EDIT_SVN_REPO_ERROR(30004,"编辑SVN仓库失败"),

    DUPLICATE_SVN_REPO_ERROR(30005,"重复添加SVN仓库"),

    ;
    private int errCode;
    private String errMsg;

    @Override
    public int getErrCode() {
        return this.errCode;
    }

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

    @Override
    public CommonError setErrMsg(String errMsg) {
        this.errMsg = errMsg ;
        return this;
    }
}

使用BusinessException自定义异常类。

import com.hbisdt.util.CommonError;

/**
 *
 * @author zhangshao
 * @date 2024/12/30 09:20
 * @description 包装器业务异常类实现
 */

public class BusinessException extends RuntimeException implements CommonError {

    private CommonError commonError;

    /**
     * 直接接收BusinessErrorEnum的传参用于构造业务异常
     * @param commonError
     */
    public BusinessException(CommonError commonError) {
        super();
        this.commonError = commonError;
    }

    public BusinessException(CommonError commonError,String errMsg){
        super();
        this.commonError = commonError;
        this.commonError.setErrMsg(errMsg);

    }

    @Override
    public int getErrCode() {
        return this.commonError.getErrCode();
    }

    @Override
    public String getErrMsg() {
        return this.commonError.getErrMsg();
    }

    @Override
    public CommonError setErrMsg(String errMsg) {
        this.commonError.setErrMsg(errMsg);
        return this;
    }
}

同时,为了使throw出去的业务异常能最终处理,定义全局异常处理类GlobalExceptionHandler

import com.hbisdt.util.BusinessErrorEnum;
import com.hbisdt.util.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 处理统一异常的handler
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(BusinessException.class)
    public Object handleBusinessException(BusinessException e) {
        log.error("BusinessException: ", e);
        return CommonResponse.error(e.getErrCode(),e.getErrMsg());
    }

    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        log.error("Default Exception: ", e);
        return CommonResponse.error(BusinessErrorEnum.UNKNOWN_ERROR);
    }

}

使用示例

 	@PostMapping("/svn/deleteRepo")
    public CommonResponse deleteRepo(@RequestBody SvnRepo svnRepo) throws BusinessException {
        log.info("删除SVN仓库,参数:{}", svnRepo.getId());
        boolean result = svnRepoService.deleteRepo(svnRepo.getId());
        log.info("删除结果:{}", result);
        if(!result){
            throw new BusinessException(BusinessErrorEnum.DEL_SVN_REPO_ERROR);
        }

        return CommonResponse.ok();
    }

业务正确,返回正确的包装类,业务抛出异常,返回错误信息和错误码。

{
    "code": 30005,
    "message": "重复添加SVN仓库",
    "data": null
}

此外,类似于10001这种参数校验错误,只需要在补充具体的参数错误原因,而无需重复定义。抛出异常时,可采用如下示例方式给出具体原因。

throw new BusinessException(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR,"邮箱不允许为空,请确认后提交");
posted @   shine-rainbow  阅读(12)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示