| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Quadarax.Foundation.Core.Exceptions
- {
- public abstract class ExceptionCodes
- {
- private readonly IDictionary<int, CodeMessageMap> _exceptionCodesCache = new Dictionary<int, CodeMessageMap>();
- protected ExceptionCodes()
- {
- _exceptionCodesCache.Add(int.MaxValue, new CodeMessageMap(int.MaxValue, "Exception with code '{0}' not found. Cannot create."));
- OnSetupCodes();
- }
- protected abstract void OnSetupCodes();
-
- protected void AddCode(int code, string message)
- {
- if (ExistsCode(code))
- throw new InvalidOperationException($"Exception code '{code}' with message '{message}' already exists in cache.");
- _exceptionCodesCache.Add(code, new CodeMessageMap(code, message));
- }
- protected bool ExistsCode(int code)
- {
- return _exceptionCodesCache.ContainsKey(code);
- }
- protected string GetMessage(int code, params string[] messageParams)
- {
- return string.Format(_exceptionCodesCache[code].Message, messageParams);
- }
- public CodeException CreateException(int code, params string[] messageParams)
- {
- return CreateException(code, null, messageParams);
- }
- public CodeException CreateException(int code, Exception innerException, params string[] messageParams)
- {
- if (!ExistsCode(code)) return new CodeException(int.MaxValue, GetMessage(code, code.ToString()));
- return new CodeException(code, GetMessage(code, messageParams));
- }
- private class CodeMessageMap
- {
- public int Code { get;}
- public string Message { get; }
- public CodeMessageMap(int code, string message)
- {
- if (string.IsNullOrEmpty(message)) throw new ArgumentNullException(nameof(message));
- Code = code;
- Message = message;
- }
- public override string ToString()
- {
- var sb = new StringBuilder();
- sb.Append(Code).Append(";").Append(Message);
- return base.ToString();
- }
- }
- }
- }
|