CommonResult.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package com.lqbz.common.result;
  2. import lombok.Data;
  3. import java.io.Serializable;
  4. import java.util.UUID;
  5. /**
  6. * 通用返回结果
  7. *
  8. * @param <T>
  9. */
  10. @Data
  11. public class CommonResult<T> extends BaseResult<T> implements Serializable {
  12. private static final long serialVersionUID = -7268040542410707954L;
  13. public CommonResult() {
  14. }
  15. public CommonResult(boolean success, String message) {
  16. this.setSuccess(success);
  17. this.setMsg(message);
  18. }
  19. public CommonResult(boolean success) {
  20. this.setSuccess(success);
  21. }
  22. public CommonResult(String code, String message) {
  23. this.setCode(code);
  24. this.setMsg(message);
  25. }
  26. public CommonResult(boolean success, String message, T data) {
  27. this.setSuccess(success);
  28. this.setMsg(message);
  29. this.setData(data);
  30. }
  31. public static CommonResult ok() {
  32. return ok(BaseErrorCode.Common.SUCCESS);
  33. }
  34. public static CommonResult fail(String message) {
  35. return fail(BaseErrorCode.Common.UNKNOWN_ERROR.getCode(), message);
  36. }
  37. public static <T> CommonResult<T> ok(IMessage message) {
  38. return baseCreate(message.getCode(), message.getMessage(), true);
  39. }
  40. public static CommonResult fail() {
  41. return fail(BaseErrorCode.Common.UNKNOWN_ERROR);
  42. }
  43. public static CommonResult fail(IMessage message) {
  44. return fail(message.getCode(), message.getMessage());
  45. }
  46. public static CommonResult fail(String code, String message) {
  47. return baseCreate(code, message, false);
  48. }
  49. private static <T> CommonResult<T> baseCreate(String code, String msg, boolean success) {
  50. CommonResult result = new CommonResult();
  51. result.setCode(code);
  52. result.setSuccess(success);
  53. result.setMsg(msg);
  54. result.setTimestamp(System.currentTimeMillis());
  55. result.setTraceId(UUID.randomUUID().toString());
  56. return result;
  57. }
  58. public CommonResult<T> addTraceId(String traceId) {
  59. this.setTraceId(traceId);
  60. return this;
  61. }
  62. public CommonResult<T> setResult(T data) {
  63. this.setData(data);
  64. return this;
  65. }
  66. public CommonResult<T> addData(T data) {
  67. this.setData(data);
  68. return this;
  69. }
  70. @Override
  71. public T getData() {
  72. return super.getData();
  73. }
  74. }