swagger响应信息码枚举设置方式

来源:互联网 发布:有没有画画软件 编辑:程序博客网 时间:2024/06/06 01:03

首先我们定义一个信息码接口

public interface IErrorCode {    /**     * 获取信息码     *     * @return     */    int getCode();    /**     * 获取信息信息     *     * @return     */    String getMsg();}

然后我们定义接口的实现类

Public enum ErrorCode implements IErrorCode {    SUCCESS(0, "SUCCESS"), FAILURE(1, "请求失败"),    SYSTEM_ERROR(1, "系统错误"), SYSTEM_BUSY(2, "系统繁忙"), PARAM_ERROR(3, "参数错误"), CFG_ERROR(4,        "配置文件错误"), FILE_UPLOAD_FAILD(5, "上传失败"), UPDATE_CACHE_ERROR(6, "更新缓存失败"),    ILLEGAL_OPERATION(7, "操作不合法"),;    private int code;    private String msg;    /**     * 构造函数     *     * @param code 错误号     * @param msg  错误信息     */    private ErrorCode(int code, String msg) {        this.code = code;        this.msg = msg;    }    /**     * 通过id来获得ErrorCode     *     * @param id     * @return     */    public static ErrorCode getErrorCodeById(int id) {        ErrorCode[] array = ErrorCode.values();        for (ErrorCode errorCode : array) {            if (errorCode.getCode() == id)                return errorCode;        }        return null;    }    /**     * <p>Title: getCode</p>     * <p>Description: 返回错误号 </p>     *     * @return code     * @see IErrorCode#getCode()     */    public int getCode() {        return code;    }    /**     * <p>Title: getMsg</p>     * <p>Description: 返回错误信息</p>     *     * @return msg     * @see IErrorCode#getMsg()     */    public String getMsg() {        return msg;    }    }

还需要定义一个统一返回的响应信息

@XmlRootElementpublic class Response {    private int errorCode;    private String errorMessage = "";    public Response(IErrorCode error) {        this.errorCode = error.getCode();        this.errorMessage = error.getMsg();        this.result = new BaseResult();    }    public Response() {        this.errorCode = ErrorCode.SUCCESS.getCode();        this.errorMessage = ErrorCode.SUCCESS.getMsg();    }    public void setIErrorCode(IErrorCode error) {        this.errorCode = error.getCode();        this.errorMessage = error.getMsg();    }    public int getErrorCode() {        return errorCode;    }    public String getErrorMessage() {        return errorMessage;    }}

然后我们就可以直接在项目中需要的地方来使用。比如我打印的异常信息。

catch (Exception e) {            // 返回异常信息            LOG.error("Exception: ", e);            return new Response(ErrorCode.FAILURE);        }

可以根据自己的需要不断扩展字段。

0 0
原创粉丝点击