using System; using System.Collections.Generic; using System.Text; namespace Quadarax.Foundation.Core.Exceptions { public abstract class ExceptionCodes { private readonly IDictionary _exceptionCodesCache = new Dictionary(); 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(); } } } }