CommandResult.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Abc.Zebus.Util.Extensions;
  6. namespace Abc.Zebus
  7. {
  8. /// <summary>
  9. /// Contains the result of a bus command.
  10. /// </summary>
  11. /// <remarks>
  12. /// <see cref="CommandResult"/> should probably not be instantiated by user code outside unit tests.
  13. /// </remarks>
  14. public class CommandResult
  15. {
  16. public CommandResult(int errorCode, string? responseMessage, object? response)
  17. {
  18. ErrorCode = errorCode;
  19. ResponseMessage = responseMessage;
  20. Response = response;
  21. }
  22. public int ErrorCode { get; }
  23. public string? ResponseMessage { get; }
  24. public object? Response { get; }
  25. public bool IsSuccess => ErrorCode == 0;
  26. public string GetErrorMessageFromEnum<T>(params object[] formatValues) where T : struct, IConvertible, IFormattable, IComparable
  27. {
  28. if (IsSuccess)
  29. return string.Empty;
  30. var value = (T)Enum.Parse(typeof(T), ErrorCode.ToString());
  31. return string.Format(((Enum)(object)value).GetAttributeDescription(), formatValues);
  32. }
  33. public static CommandResult Success(object? response = null)
  34. => new CommandResult(0, null, response);
  35. public static CommandResult Error(int errorCode = 1, string? responseMessage = null)
  36. {
  37. if (errorCode == 0)
  38. throw new ArgumentException("error code cannot be zero", nameof(errorCode));
  39. return new CommandResult(errorCode, responseMessage, null);
  40. }
  41. internal static ErrorStatus GetErrorStatus(IEnumerable<Exception> exceptions)
  42. {
  43. return exceptions.FirstOrDefault() is MessageProcessingException ex
  44. ? new ErrorStatus(ex.ErrorCode, ex.Message)
  45. : ErrorStatus.UnknownError;
  46. }
  47. public override string ToString()
  48. {
  49. var text = new StringBuilder(IsSuccess ? "Success" : $"Error, ErrorCode: {ErrorCode}");
  50. if (ResponseMessage != null)
  51. text.Append($", ResponseMessage: [{ResponseMessage}]");
  52. if (Response != null)
  53. text.Append($", Response: [{Response}]");
  54. return text.ToString();
  55. }
  56. }
  57. }