CommonResult.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package com.persagy.framework.common.pojo;
  2. import com.persagy.framework.common.exception.ErrorCode;
  3. import com.persagy.framework.common.exception.ServiceException;
  4. import com.persagy.framework.common.exception.enums.GlobalErrorCodeConstants;
  5. import com.fasterxml.jackson.annotation.JsonIgnore;
  6. import lombok.Data;
  7. import org.springframework.util.Assert;
  8. import java.io.Serializable;
  9. import java.util.Objects;
  10. /**
  11. * 通用返回
  12. *
  13. * @param <T> 数据泛型
  14. */
  15. @Data
  16. public class CommonResult<T> implements Serializable {
  17. /**
  18. * 错误码
  19. *
  20. * @see ErrorCode#getCode()
  21. */
  22. private Integer code;
  23. /**
  24. * 返回数据
  25. */
  26. private T data;
  27. /**
  28. * 错误提示,用户可阅读
  29. *
  30. * @see ErrorCode#getMsg() ()
  31. */
  32. private String msg;
  33. /**
  34. * 将传入的 result 对象,转换成另外一个泛型结果的对象
  35. *
  36. * 因为 A 方法返回的 CommonResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。
  37. *
  38. * @param result 传入的 result 对象
  39. * @param <T> 返回的泛型
  40. * @return 新的 CommonResult 对象
  41. */
  42. public static <T> CommonResult<T> error(CommonResult<?> result) {
  43. return error(result.getCode(), result.getMsg());
  44. }
  45. public static <T> CommonResult<T> error(Integer code, String message) {
  46. Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "code 必须是错误的!");
  47. CommonResult<T> result = new CommonResult<>();
  48. result.code = code;
  49. result.msg = message;
  50. return result;
  51. }
  52. public static <T> CommonResult<T> error(ErrorCode errorCode) {
  53. return error(errorCode.getCode(), errorCode.getMsg());
  54. }
  55. public static <T> CommonResult<T> success(T data) {
  56. CommonResult<T> result = new CommonResult<>();
  57. result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
  58. result.data = data;
  59. result.msg = "";
  60. return result;
  61. }
  62. public static boolean isSuccess(Integer code) {
  63. return Objects.equals(code, GlobalErrorCodeConstants.SUCCESS.getCode());
  64. }
  65. @JsonIgnore // 避免 jackson 序列化
  66. public boolean isSuccess() {
  67. return isSuccess(code);
  68. }
  69. @JsonIgnore // 避免 jackson 序列化
  70. public boolean isError() {
  71. return !isSuccess();
  72. }
  73. // ========= 和 Exception 异常体系集成 =========
  74. /**
  75. * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常
  76. */
  77. public void checkError() throws ServiceException {
  78. if (isSuccess()) {
  79. return;
  80. }
  81. // 业务异常
  82. throw new ServiceException(code, msg);
  83. }
  84. public static <T> CommonResult<T> error(ServiceException serviceException) {
  85. return error(serviceException.getCode(), serviceException.getMessage());
  86. }
  87. }