Result.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using Quadarax.Foundation.Core.Exceptions;
  4. using System.Linq;
  5. using Quadarax.Foundation.Core.Value.Extensions;
  6. namespace Quadarax.Foundation.Core.Data
  7. {
  8. public class Result : IResult
  9. {
  10. #region *** Properties ***
  11. public bool IsSuccess { get; protected set; }
  12. public IEnumerable<IError> Errors => _errors;
  13. public static IResult Ok => new Result();
  14. public static IResult Fail => new Result(false, new List<IError> { new Error("Operation failed", 0, ErrorLevelEnum.Error) });
  15. #endregion
  16. #region *** Private Fields ***
  17. private readonly IList<IError> _errors = new List<IError>();
  18. #endregion
  19. #region *** Constructors ***
  20. public Result() : this(true, null)
  21. {
  22. }
  23. public Result(IEnumerable<IError> errors) : this(false, errors)
  24. {
  25. }
  26. public Result(bool isSuccess, IEnumerable<IError>? errors)
  27. {
  28. errors ??= new List<IError>();
  29. IsSuccess = isSuccess;
  30. _errors.AddRange(errors);
  31. }
  32. #endregion
  33. #region *** Operations ***
  34. public void SetSuccess(bool isSuccess)
  35. {
  36. IsSuccess = isSuccess;
  37. }
  38. public void AddError(IError error)
  39. {
  40. if (error == null)
  41. throw new ArgumentNullException(nameof(error));
  42. _errors.Add(error);
  43. }
  44. public void ClearErrors()
  45. {
  46. _errors.Clear();
  47. }
  48. public object? GetValue()
  49. {
  50. return null;
  51. }
  52. public void ThrowIfError()
  53. {
  54. if (IsSuccess) return;
  55. throw new AggregateException(Errors.Select(e => e.AsCodeException()));
  56. }
  57. public AggregateException? ToAggregateException()
  58. {
  59. if (IsSuccess)
  60. return null;
  61. var errors = new List<CodeException>();
  62. foreach (var e in Errors)
  63. {
  64. errors.Add(e.AsCodeException());
  65. }
  66. return new AggregateException(errors);
  67. }
  68. #endregion
  69. }
  70. }