ExceptionCodes.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Quadarax.Foundation.Core.Exceptions
  5. {
  6. public abstract class ExceptionCodes
  7. {
  8. private readonly IDictionary<int, CodeMessageMap> _exceptionCodesCache = new Dictionary<int, CodeMessageMap>();
  9. protected ExceptionCodes()
  10. {
  11. _exceptionCodesCache.Add(int.MaxValue, new CodeMessageMap(int.MaxValue, "Exception with code '{0}' not found. Cannot create."));
  12. OnSetupCodes();
  13. }
  14. protected abstract void OnSetupCodes();
  15. protected void AddCode(int code, string message)
  16. {
  17. if (ExistsCode(code))
  18. throw new InvalidOperationException($"Exception code '{code}' with message '{message}' already exists in cache.");
  19. _exceptionCodesCache.Add(code, new CodeMessageMap(code, message));
  20. }
  21. protected bool ExistsCode(int code)
  22. {
  23. return _exceptionCodesCache.ContainsKey(code);
  24. }
  25. protected string GetMessage(int code, params string[] messageParams)
  26. {
  27. return string.Format(_exceptionCodesCache[code].Message, messageParams);
  28. }
  29. public CodeException CreateException(int code, params string[] messageParams)
  30. {
  31. return CreateException(code, null, messageParams);
  32. }
  33. public CodeException CreateException(int code, Exception innerException, params string[] messageParams)
  34. {
  35. if (!ExistsCode(code)) return new CodeException(int.MaxValue, GetMessage(code, code.ToString()));
  36. return new CodeException(code, GetMessage(code, messageParams));
  37. }
  38. private class CodeMessageMap
  39. {
  40. public int Code { get;}
  41. public string Message { get; }
  42. public CodeMessageMap(int code, string message)
  43. {
  44. if (string.IsNullOrEmpty(message)) throw new ArgumentNullException(nameof(message));
  45. Code = code;
  46. Message = message;
  47. }
  48. public override string ToString()
  49. {
  50. var sb = new StringBuilder();
  51. sb.Append(Code).Append(";").Append(Message);
  52. return base.ToString();
  53. }
  54. }
  55. }
  56. }