package com.ots.project.exam.dto; import com.ots.common.enums.ResponseCode; import com.ots.common.enums.SystemCode; import com.ots.project.common.exception.BaseException; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DuplicateKeyException; /** * @author Shawn */ @Slf4j public class RestResponse { private int code; private String message; private T response; public RestResponse(int code, String message) { this.code = code; this.message = message; } public RestResponse(int code, String message, T response) { this.code = code; this.message = message; this.response = response; } public static RestResponse fail(Integer code, String msg) { return new RestResponse<>(code, msg); } /** * 增加错误编码统一处理 * * @param enumCode * @return */ public static RestResponse fail(ResponseCode enumCode) { return new RestResponse<>(enumCode.getCode(), enumCode.getMessage()); } /** * 异常结合枚举方便异常统一处理 * * @param e * @return */ public static RestResponse fail(Exception e) { if (e instanceof BaseException) { BaseException e1 = (BaseException) e; return new RestResponse<>(e1.getResponseEnum().getCode(), e1.getMessage()); } else if (e instanceof DuplicateKeyException) { log.error("DuplicateKeyException:", e); return new RestResponse<>(998, "复合索引冲突,数据不能重复提交!"); } else { return new RestResponse<>(999, e.getMessage()); } } public static RestResponse ok() { SystemCode systemCode = SystemCode.OK; return new RestResponse<>(systemCode.getCode(), systemCode.getMessage()); } public static RestResponse ok(F response) { SystemCode systemCode = SystemCode.OK; return new RestResponse<>(systemCode.getCode(), systemCode.getMessage(), response); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getResponse() { return response; } public void setResponse(T response) { this.response = response; } }