Springboot 项目中关于异常的设计
ErrorCode
错误码接口
public interface ErrorCode {
int getCode();
String getMsg();
}
ErrorCodeEnum
自定义错误码枚举(参考支付宝开发平台设计)
@Getter
public enum ErrorCodeEnum implements ErrorCode {
SUCCESS(10000,"success."),
UNKNOW_ERROR(20000,"unknow error."),
UNKNOW_PERMISSION(20001,"unknow permission."),
PARAM_MISS(40001,"missing param."),
PARAM_ILLEGAL(40002,"illegal param."),
BUSINESS_FAIL(40004,"business fail."),
PERMISSION_DENY(40006,"permission denied."),
CALL_LIMTIED(40005,"call limited.")
;
private int code;
private String msg;
;
ErrorCodeEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
CustomException
自定义异常
@Data
public class CustomException extends RuntimeException{
private ErrorCode errorCode;
private String subCode;
private String subMsg;
public CustomException(ErrorCode errorCode, String subCode, String subMsg) {
super(errorCode.getMsg());
this.subCode = subCode;
this.subMsg = subMsg;
}
}
GlobalExceptionHandler
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseErrorResult customException(CustomException e) {
log.error(e.getMessage(), e);
ResponseErrorResult response = new ResponseErrorResult();
response.setCode(e.getErrorCode().getCode());
response.setMsg(e.getErrorCode().getMsg());
response.setSubCode(e.getSubCode());
response.setSubMsg(e.getSubMsg());
return response;
}
@ExceptionHandler(Exception.class)
public ResponseErrorResult handleException(Exception e) {
log.error(e.getMessage(), e);
ResponseErrorResult response = new ResponseErrorResult();
response.setCode(ErrorCodeEnum.UNKNOW_ERROR.getCode());
response.setMsg(ErrorCodeEnum.UNKNOW_ERROR.getMsg());
response.setSubCode(e.getClass().getName());
response.setSubMsg(e.getMessage());
return response;
}
@Data
private class ResponseErrorResult{
private int code;
private String msg;
private String subCode;
private String subMsg;
}
}
说明:CustomException会被捕获,返回具体的异常码与异常信息。如果需要捕获其它异常自定义返回信息,请照着CustomException的方式添加。
使用案例
@PostMapping("/add")
public ResponseResult addFacePerson(FacePersonForm form, MultipartFile file) throws IOException {
ImageInfo rgbData = ImageFactory.getRGBData(file.getBytes());
List<FaceInfo> faceInfoList = faceEngineService.detectFaces(rgbData);
if (CollectionUtil.isEmpty(faceInfoList)) {
throw new CustomException(ErrorCodeEnum.PARAM_ILLEGAL,"not recognize face.","没有检测到人脸信息。");
}
FacePerson facePerson = new FacePerson();
byte[] feature = faceEngineService.extractFaceFeature(rgbData, faceInfoList.get(0));
facePerson.setName(form.getName());
facePerson.setFeature(feature);
facePersonService.add(facePerson);
return ResponseResult.ok();
}
调用示例
{
code:40002,
msg:"illegal param.",
subCode:"not recognize face.",
subMsg:""没有检测到人脸信息。"
}
参考资料
|