CommonResult.java 2.7 KB

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