错误码定义
-
错误码基类
public interface BaseErrorCodeEnum <C, N>{
C getCode();
N getName();
}
-
具体业务错误码定义现类
public enum ServicesErrorCodeEnum implements BaseErrorCodeEnum<Integer, String> {
/**
* 基础服务 1001XX
*/
SERVICES_NOT_EXIEST(100100, "服务不存在"),
SDK_NOT_EXIEST(100101, "服务sdk不存在");
private int code;
private String name;
ServicesErrorCodeEnum(int code, String name) {
this.code = code;
this.name = name;
}
@Override
public Integer getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-
业务异常处理
throw new BadRequestException(ServicesErrorCodeEnum.SDK_NOT_EXIEST);
-
异常返回模型定义
public class ErrorInfo implements Serializable { public static final int SYS_ERROR = 500; private static final long serialVersionUID = -5318560134107301674L; /** * 错误的标志码 */ private Integer code; /** * 错误的描述信息,如果需要传递format参数,则用 # # 分隔 */ private String message; /** * 额外的参数信息,默认替换 message 中 #test# 参数 */ @SerializedName("extra_param") private Map<String, Object> extraParam; private transient Boolean needFormat = false; public static ErrorInfo builder() { return new ErrorInfo(); } public ErrorInfo build() { return this; } public ErrorInfo code(Integer code) { this.code = code; return this; } public ErrorInfo message(String message) { this.message = message; return this; } public ErrorInfo extraParam(Map<String, Object> extraParam) { this.extraParam = extraParam; return this; } public ErrorInfo needFormat(boolean needFormat) { this.needFormat = needFormat; return this; } public Integer getCode() { return code; } public String getMessage() { if(null != extraParam && needFormat) { extraParam.forEach((k, v) ->{ String key = "#" + k + "#"; if(message.contains(key)) { message = message.replaceAll(key, String.valueOf(v)); } }); } return message; } public Map<String, Object> getExtraParam() { return extraParam; } public Boolean getNeedFormat() { return needFormat; } /** * @param code the code to set */ public void setCode(Integer code) { this.code = code; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @param extraParam the extraParam to set */ public void setExtraParam(Map<String, Object> extraParam) { this.extraParam = extraParam; } /** * @param needFormat the needFormat to set */ public void setNeedFormat(Boolean needFormat) { this.needFormat = needFormat; } }
-
业务异常捕获
@ControllerAdvice
public class GlobalExceptionHandler {
private static final LogUtil log = LogUtil.newInstance(GlobalExceptionHandler.class);
@ExceptionHandler(value = BadRequestException.class)
@ResponseBody
public ErrorInfo validateErrorHandler(HttpServletRequest req, HttpServletResponse rep, BadRequestException e) throws Exception {
rep.setStatus(HttpStatus.BAD_REQUEST.value());
log.error("业务处理异常",e);
return e.getErrorInfo();
}
}