定义通用返回包装类
包装返回正确的数据格式,返回类型示例
{"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);}
使用BusinessEnum实现该抽象类,使用BusinessErrorEnum定义业务异常
import lombok.AllArgsConstructor;@AllArgsConstructor
public enum BusinessErrorEnum implements CommonError{// 通用错误类型10001PARAMETER_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;@Overridepublic int getErrCode() {return this.errCode;}@Overridepublic String getErrMsg() {return this.errMsg;}@Overridepublic 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);}@Overridepublic int getErrCode() {return this.commonError.getErrCode();}@Overridepublic String getErrMsg() {return this.commonError.getErrMsg();}@Overridepublic 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,"邮箱不允许为空,请确认后提交");