You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuResult.cs 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using Luticate2.Utils.Controllers;
  3. namespace Luticate2.Utils.Dbo.Result
  4. {
  5. public class LuResult<T>
  6. {
  7. public LuStatus Status { get; set; }
  8. public bool Success => Status == LuStatus.Success;
  9. public string PublicDetails { get; set; }
  10. public string PrivateDetails { get; set; }
  11. public string StackTrace { get; set; }
  12. public Exception Exception { get; set; }
  13. public T Data { get; set; }
  14. protected LuResult()
  15. {
  16. }
  17. public static LuResult<T> Ok(T data)
  18. {
  19. return new LuResult<T>
  20. {
  21. StackTrace = new Exception().StackTrace,
  22. Data = data,
  23. Status = LuStatus.Success
  24. };
  25. }
  26. public static LuResult<T> Error(LuStatus status, string privateDetails, string publicDetails = null)
  27. {
  28. return new LuResult<T>
  29. {
  30. PublicDetails = publicDetails == "" ? privateDetails : publicDetails,
  31. PrivateDetails = privateDetails,
  32. StackTrace = new Exception().StackTrace,
  33. Status = status
  34. };
  35. }
  36. public static LuResult<T> Error(LuStatus status, Exception e, string publicDetails = null)
  37. {
  38. return new LuResult<T>
  39. {
  40. PublicDetails = publicDetails,
  41. PrivateDetails = e.ToString(),
  42. StackTrace = new Exception().StackTrace,
  43. Exception = e,
  44. Status = status
  45. };
  46. }
  47. public static LuResult<T> Error<T2>(LuResult<T2> other)
  48. {
  49. return new LuResult<T>
  50. {
  51. Status = other.Status,
  52. PublicDetails = other.PublicDetails,
  53. PrivateDetails = other.PrivateDetails,
  54. StackTrace = other.StackTrace,
  55. Exception = other.Exception
  56. };
  57. }
  58. public LuResult<T2> To<T2>()
  59. {
  60. return LuResult<T2>.Error(this);
  61. }
  62. public LuResult<T2> To<T2>(Func<T, T2> convert)
  63. {
  64. return new LuResult<T2>
  65. {
  66. Data = Success ? convert(Data) : default(T2),
  67. Status = Status,
  68. PublicDetails = PublicDetails,
  69. PrivateDetails = PrivateDetails,
  70. StackTrace = StackTrace,
  71. Exception = Exception
  72. };
  73. }
  74. public static implicit operator bool(LuResult<T> res)
  75. {
  76. return res.Success;
  77. }
  78. public void Throw()
  79. {
  80. throw new LuResultException(To<object>());
  81. }
  82. public LuResult<T> ThrowIfNotSuccess()
  83. {
  84. if (!this)
  85. {
  86. Throw();
  87. }
  88. return this;
  89. }
  90. }
  91. }