CodeException.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Quadarax.Foundation.Core.Attributes;
  5. using Quadarax.Foundation.Core.Reflection;
  6. namespace Quadarax.Foundation.Core.Exceptions
  7. {
  8. [Serializable]
  9. public class CodeException : Exception
  10. {
  11. private static IDictionary<int, string> _codeMessageCache;
  12. public CodeException(int code, string message, Exception innerException) : base(message, innerException)
  13. {
  14. this.SetCode(code);
  15. }
  16. public CodeException(int code, string message) : base(message)
  17. {
  18. this.SetCode(code);
  19. }
  20. public CodeException(int code) : base()
  21. {
  22. this.SetCode(code);
  23. }
  24. public static void InitMessageCache(object exceptionCodesStaticClass)
  25. {
  26. if (_codeMessageCache == null)
  27. _codeMessageCache = new Dictionary<int, string>();
  28. var consts = exceptionCodesStaticClass.GetType().GetFields(BindingFlags.Public | BindingFlags.Static);
  29. foreach (FieldInfo con in consts)
  30. {
  31. var attr = AttributeQuery<CodeMessageExceptionItemAttribute>.Get(con);
  32. if (attr != null)
  33. {
  34. if (!_codeMessageCache.ContainsKey(attr.Code))
  35. {
  36. _codeMessageCache.Add(attr.Code, con.GetValue(exceptionCodesStaticClass)?.ToString());
  37. }
  38. else
  39. {
  40. _codeMessageCache[attr.Code] = con.GetValue(exceptionCodesStaticClass)?.ToString();
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }