这篇文章给大家分享的是有关java使用枚举封装错误码及错误信息的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
枚举封装错误码及错误信息
使用枚举类型来封装project中所需要的错误码和错误信息,十分方便。
用法如下
package com.dear.simpler.dbservice; public enum DBServiceError { //RPC层调用错误码 DB_SERVICE_OK(20100,"服务正常"),DB_SERVICE_DBDAO_ERROR(20104,"返回数据库的具体异常信息"),DB_SERVICE_SPEAKER_NOT_EXISTED(20108,"数据库中没有要查询的speaker"),DB_SERVICE_SPEAKER_HAVE_NOT_VP(20109,"speaker中没有对应的voiceprint"),DB_SERVICE_UNKNOWN_ERROR(20101,"未知异常"),DB_SERVICE_AGENT_ERROR(20102,"DBServiceAgent异常"),DB_SERVICE_NETWORK_ERROR (20103,"网络异常"),DB_SERVICE_INVALID_FUNCTION(20105,"方法名不存在"),DB_SERVICE_INVALID_PARAMETER(20106,"方法参数错误"),DB_SERVICE_FUNCTION_NO_ACCESS(20107,"对此方法无访问权限"); private String msg; private int code; private DBServiceError(int code,String msg) { this.code=code; this.msg=msg; } public String getMsg() { return this.msg; } public int getCode() { return this.code; }}
使用时:
DBServiceError.DB_SERVICE_NETWORK_ERROR.getCode();
DBServiceError.DB_SERVICE_NETWORK_ERROR.getMsg();
封装返回结果类和枚举错误码
枚举错误码
public emum ErrorCode{ FAILED(601,"操作失败"), AUTH_ERROR(401,"认证失败"), SYS_ERROR(500,"系统错误"), PARAM_ERROR(400,"参数错误"), UNKNOWN_ERROR(499,"未知错误"); private int code; private String message; private ErrorCode(int code, String message) { this.code=code; this.message=message; } public String getMessage() { return this.message; } public int getCode() { return this.code; }}
封装返回结果类
public class JsonResult { private int status = 0; private String msg = "success"; private Object data; // 几个常用方法 public JsonResult success() { return new JsonResult(); } public JsonResult success(Object data) { return new JsonResult(data); } public JsonResult error(ErrorCode errorCode) { return new JsonResult(errorCode.getCode(), errorCode.getMessage()); } public JsonResult error(int state, String message) { return new JsonResult(state, message); } public JsonResult error(int state, String message, Object data) { return new JsonResult(state, message, data); } // 几个构造方法 public JsonResult() { } public JsonResult(Object data) { this.data = data; } public JsonResult(Integer state, String message) { this.state = state; this.message = message; } public JsonResult(Integer state, String message, Object data) { this.state = state; this.message = message; this.data = data; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; }}
感谢各位的阅读!关于“java使用枚举封装错误码及错误信息的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!