R.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package com.futu.course.common.entity;
  2. import com.futu.course.common.exception.ApiException;
  3. import lombok.Data;
  4. import java.io.Serializable;
  5. import java.util.Optional;
  6. /**
  7. * @className: R
  8. * @Description:
  9. * @author: zhangxiong
  10. * @date: 2022/4/23/0023 20:52
  11. */
  12. @Data
  13. public class R<T> implements Serializable {
  14. /**
  15. * serialVersionUID
  16. */
  17. private static final long serialVersionUID = 1L;
  18. /**
  19. * 业务错误码
  20. */
  21. private long code;
  22. /**
  23. * 结果集
  24. */
  25. private T data;
  26. /**
  27. * 描述
  28. */
  29. private String msg;
  30. public R() {
  31. // to do nothing
  32. }
  33. public R(IErrorCode errorCode) {
  34. errorCode = Optional.ofNullable(errorCode).orElse(ApiErrorCode.FAILED);
  35. this.code = errorCode.getCode();
  36. this.msg = errorCode.getMsg();
  37. }
  38. public static <T> R<T> ok(T data) {
  39. ApiErrorCode aec = ApiErrorCode.SUCCESS;
  40. if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
  41. aec = ApiErrorCode.FAILED;
  42. }
  43. return restResult(data, aec);
  44. }
  45. public static <T> R<T> failed(String msg) {
  46. return restResult(null, ApiErrorCode.FAILED.getCode(), msg);
  47. }
  48. public static <T> R<T> failed(int code,String msg) {
  49. return restResult(null, code, msg);
  50. }
  51. public static <T> R<T> failed(IErrorCode errorCode) {
  52. return restResult(null, errorCode);
  53. }
  54. public static <T> R<T> restResult(T data, IErrorCode errorCode) {
  55. return restResult(data, errorCode.getCode(), errorCode.getMsg());
  56. }
  57. public static <T> R<T> restResult(T data, long code, String msg) {
  58. R<T> apiResult = new R<>();
  59. apiResult.setCode(code);
  60. apiResult.setData(data);
  61. apiResult.setMsg(msg);
  62. return apiResult;
  63. }
  64. public boolean ok() {
  65. return ApiErrorCode.SUCCESS.getCode() == code;
  66. }
  67. /**
  68. * 服务间调用非业务正常,异常直接释放
  69. */
  70. public T serviceData() {
  71. if (!ok()) {
  72. throw new ApiException(this.msg);
  73. }
  74. return data;
  75. }
  76. }