目录
ApiException extends RuntimeException
介绍:
接口调用:项目构建之服务之间的接口调用通常需要一个通用的返回值,即ApiResult。
异常处理:业务处理时,会需要有很多地方进行逻辑卡控,抛出异常等,也需要返回一个通用的封装对象,即ApiResult。
ResultUtil的作用:就是将原本返回的对象进行再次封装,封装成ApiResult通用对象
ResultUtil
import com.google.gson.Gson;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
public class ResultUtil {
private static ApiInfo basicInfo = new ApiInfo();
public ResultUtil() {
}
public static ApiInfo getBasicInfo() {
return basicInfo;
}
public static ApiResult setResult(Integer httpCode, ResultCode resultCode, Object object, String addiInfo) {
ApiResult<Object> result = new ApiResult();
result.setHttpCode(httpCode);
result.setCode(resultCode.getCode());
result.setMsg(resultCode.getMsg());
result.setMsgCh(resultCode.getMsgCh());
result.setData(object);
result.setAddiInfo(addiInfo);
result.setBasicInfo(basicInfo);
return result;
}
public static ApiResult success(Object object, String addiInfo) {
return setResult(HttpStatus.OK.value(), ResultCode.SUCCESS, object, addiInfo);
}
public static ApiResult success(ResultCode resultCode) {
return setResult(HttpStatus.OK.value(), resultCode, (Object)null, (String)null);
}
public static ApiResult success(Object object) {
return setResult(HttpStatus.OK.value(), ResultCode.SUCCESS, object, (String)null);
}
public static ApiResult success(Integer httpCode, Object object, String addiInfo) {
return setResult(httpCode, ResultCode.SUCCESS, object, addiInfo);
}
public static ApiResult success() {
return success((Object)null, (String)null);
}
public static ApiResult error(ResultCode resultCode) {
return setResult(HttpStatus.BAD_REQUEST.value(), resultCode, (Object)null, (String)null);
}
public static ApiResult error(ResultCode resultCode, String addiInfo) {
return setResult(HttpStatus.BAD_REQUEST.value(), resultCode, (Object)null, addiInfo);
}
public static ApiResult error(Integer httpCode, ResultCode resultCode, String addiInfo) {
return setResult(httpCode, resultCode, (Object)null, addiInfo);
}
public static ApiResult error(ResultCode resultCode, String msgEn, String msgCh) {
ApiResult result = new ApiResult();
result.setHttpCode(HttpStatus.BAD_REQUEST.value());
result.setCode(resultCode.getCode());
result.setMsg(msgEn);
result.setMsgCh(msgCh);
return result;
}
public static ApiResult handleApiException(Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException)e;
return apiException.getApiResult();
} else {
return error(ResultCode.UNKONW_ERROR, e.toString());
}
}
public static ApiResult<Object> getApiResult(String JsonStr) {
ApiResult<Object> result = new ApiResult();
JSONObject jsonObject = new JSONObject(JsonStr);
ApiInfo apiInfo = new ApiInfo();
Object object = jsonObject.get("basicInfo");
if (null != object) {
Gson gson = new Gson();
apiInfo = (ApiInfo)gson.fromJson(object.toString(), ApiInfo.class);
}
result.setBasicInfo(apiInfo);
result.setCode(jsonObject.getInt("code"));
result.setMsg(jsonObject.getString("msg"));
result.setMsgCh(jsonObject.getString("msgCh"));
Object addInfo = jsonObject.get("addiInfo");
if (addInfo != null) {
result.setAddiInfo(addInfo.toString());
}
object = jsonObject.get("data");
if (null != object) {
result.setData(object);
}
return result;
}
public static String getCodeInfo() {
boolean ifStart = true;
String jsonStr = "{[";
ResultCode[] var2 = ResultCode.values();
int var3 = var2.length;
for(int var4 = 0; var4 < var3; ++var4) {
ResultCode resultCode = var2[var4];
if (ifStart) {
jsonStr = jsonStr + "{";
ifStart = false;
} else {
jsonStr = jsonStr + ",{";
}
jsonStr = jsonStr + "\"code\":" + resultCode.getCode() + ",";
jsonStr = jsonStr + "\"msg\":\"" + resultCode.getMsg() + "\",";
jsonStr = jsonStr + "\"msgCh\":\"" + resultCode.getMsgCh() + "\"}";
}
jsonStr = "]}";
return jsonStr;
}
}
ApiResult
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(
value = "ApiResult",
description = "统一错误码"
)
public class ApiResult<T> {
@ApiModelProperty("http专用错误码")
private Integer httpCode;
@ApiModelProperty(
value = "Hierway 业务错误码",
example = "200: Success; 201: Failure"
)
private Integer code;
@ApiModelProperty("错误码信息")
private String msg;
@ApiModelProperty("中文错误码信息")
private String msgCh;
@ApiModelProperty("错误码额外信息,当msg不能满足的情况下使用")
private String addiInfo;
@ApiModelProperty("基本信息,比如模块名,IP等")
private ApiInfo basicInfo;
@ApiModelProperty("返回值的内容")
private T data;
public ApiResult() {
}
get set tostring 省略
}
ApiException extends RuntimeException
public class ApiException extends RuntimeException {
private ApiResult apiResult;
public ApiResult getApiResult() {
return this.apiResult;
}
public void setApiResult(ApiResult apiResult) {
this.apiResult = apiResult;
}
public ApiException(ResultCode resultCode) {
this.apiResult = ResultUtil.error(resultCode);
}
public ApiException(ResultCode resultCode, String addiInfo) {
this.apiResult = ResultUtil.error(resultCode, addiInfo);
}
public String toString() {
return "ApiException{apiResult=" + this.apiResult + '}';
}
}
ApiInfo
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(
value = "ApiInfo",
description = "API基本信息"
)
public class ApiInfo {
@ApiModelProperty("服务模块名")
private String module_name = "unknown name";
@ApiModelProperty("服务模块IP地址")
private String ip_address = "0.0.0.0";
@ApiModelProperty("服务模块端口号")
private short udp_port = 0;
@ApiModelProperty("其它信息")
private String addiInfo = "no additional information";
ApiInfo() {
}
get set tostring 省略
}
ResultCode
public enum ResultCode {
UNKONW_ERROR(-1, "Unknown error", "未知错误"),
SUCCESS(200, "Success", "成功"),
FAILURE(201, "Failure", "失败"),
NO_DATA_FOUND(202, "Data not found", "未找到数据"),
COMMON_BASE_CODE(1000, "Common Base Error Code", "通用基本错误码"),
COMMON_FAILSURE(1001, "Failsure", "失败"),
COMMON_NO_DATA_FOUND(1002, "Data not found", "未找到数据"),
ADD_FAILED(1003, "Add failed", "添加失败"),
UPDATE_FAILED(1004, "Updated failed", "更新失败"),
DELETE_FAILED(1005, "Delete failed", "删除失败"),
DATA_ALREADY_EXIST(1006, "Data already existed", "数据已经存在"),
NOT_SUITABLE_OPERATION(1007, "Not suitable operation", "不适合的操作"),
DATABASE_OP_FAILED(1008, "Operate database failed", "操作数据库失败"),
NO_PERMISSION(1009, "Permission is needed", "权限不够,需要开通权限"),
SERVER_ERROR(1010, "Server error", "服务器错误"),
AUTH_ERROR(1011, "Authentication failed ", "鉴权失败"),
PARAMS_ERROR(1012, "Parameter error", "参数错误"),
JSON_PARSE_ERROR(1013, "Json parse error", "JSON解析错误"),
ILLEAGAL_STRING(1014, "Illegal string", "非法字符串"),
CERTIFICATE_EXPIRED(1015, "Client certificate has expired or is not yet valid", "客户端证书过期或已无效"),
CERTIFICATE_INVALID(1016, "Client certificate is untrusted or invalid.", "客户端证书不可信或无效"),
SYSTEM_BASE_CODE(2000, "System Base Error Code", "系统基本错误码"),
DO_NOT_OPERATE(10000, "Do not operate", "不操作"),
THERE_ARE_STILL_PROCESSES_WITHOUT_MOUNT_PRODUCTIVITY_UNITS(10001, "There are still processes without mount productivity units", "未定义"),
THE_PRODUCTIVITY_UNIT_HAS_BEEN_USED(10002, "The productivity unit has been used", "未定义"),
NO_NEED_CONFIGURE(10003, "The process does not require configuration of a productivity unit", "未定义");
private Integer code;
private String msg;
private String msgCh;
private ResultCode(Integer code, String msg, String msgCh) {
this.code = code;
this.msg = msg;
this.msgCh = msgCh;
}
public Integer getCode() {
return this.code;
}
public String getMsg() {
return this.msg;
}
public String getMsgCh() {
return this.msgCh;
}
}
捕获异常处理类ApiExceptionHandle
@ControllerAdvice
public class ApiExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ApiExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResult handle(Exception e) {
logger.error("全局异常:{}", e);
return ResultUtil.handleApiException(e);
}
}