public class RestErrorResponse { private Integer errorCode; private String message; private Object details; private JSONObject result; private RestErrorResponse() { } public static RestErrorResponse build() { return new RestErrorResponse(); } public Integer getErrorCode() { return errorCode; } public RestErrorResponse setErrorCode(Integer errorCode) { this.errorCode = errorCode; return this; } public String getMessage() { return message; } public RestErrorResponse setMessage(String message) { this.message = message; return this; } public Object getDetails() { return details; } public RestErrorResponse setDetails(Object details) { this.details = details; return this; } public void setResult(JSONObject result) { this.result = result; } @Override public String toString() { return getResult(); } public String getResult() { result = new JSONObject(); JSONObject errorJson = new JSONObject(); errorJson.put("code", errorCode); errorJson.put("message", message); errorJson.put("details", details); result.put("error", errorJson); return result.toString(); } }
public enum RestResponseEnum { /* */ SUCCESS(200, "成功"), UNKNOWN_ERROR(-1, "未知错误"), EQUIPMENT_ERROR(511, "操作设备失败"), EXCEL_DOWNLOAD_ERROR(516, "EXCEL下载失败"), EXCEL_UPLOAD_ERROR(517, "EXCEL上传失败"), /* error result about login*/ LOGIN_ERROR(501, "用户登录失败"), ADMIN_LOGIN_ERROR(502, "管理员登录失败"), /* error result about user*/ USER_ERROR(506, "操作用户失败"); private Integer code; private String msg; RestResponseEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } }
@RestController public class EquipmentController { @Autowired private EquipmentService equipmentService; @DeleteMapping("/v1/equipment") public Object deleteEquipment(HttpServletRequest request, HttpServletResponse response, @RequestParam("equipmentId") String equipmentId) { boolean isSuccess = equipmentService.delete(equipmentId); if (isSuccess) { response.setStatus(RestResponseEnum.SUCCESS.getCode()); return equipmentId; } return RestErrorResponse.build().setErrorCode(RestResponseEnum.EQUIPMENT_ERROR.getCode()).setMessage(RestResponseEnum.EQUIPMENT_ERROR.getMsg()).getResult(); }