12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- using System.Globalization;
- namespace MTWorkHR.Core.Global
- {
- public class AppException : Exception
- {
- /// <summary>
- /// Gets the error number associated with this exception.
- /// </summary>
- public readonly ExceptionEnum ErrorNumber;
- /// <summary>
- /// Gets the formatted error message.
- /// </summary>
- public string ErrorMessage { get; private set; } = string.Empty;
- public AppException(string errorMessage) : base(errorMessage)
- {
- ErrorMessage = errorMessage;
- }
- /// <summary>
- /// Creates a new instance of <see cref="AppException"/> using an error number, language, and optional format arguments.
- /// </summary>
- /// <param name="errorNumber">The error number (enum) representing the exception type.</param>
- /// <param name="language">The language code (e.g., "en" or "ar").</param>
- /// <param name="args">Optional arguments to format the error message.</param>
- public AppException(ExceptionEnum errorNumber, params object[] args) : base()
- {
- ErrorNumber = errorNumber;
- ErrorMessage = GetMessage(errorNumber, GlobalInfo.lang?? "en", args);
- // Initialize the base exception with the localized error message.
- this.SetErrorMessage();
- }
- /// <summary>
- /// Sets the exception message for the base exception class.
- /// </summary>
- private void SetErrorMessage()
- {
- base.HelpLink = ErrorNumber.ToString(); // Optional: Use error number as a link or reference
- base.Source = nameof(AppException); // Optional: Set the exception source
- }
- /// <summary>
- /// Retrieves the error message based on the provided error code and language.
- /// </summary>
- /// <param name="code">The error number (enum).</param>
- /// <param name="language">The language code (default: "en").</param>
- /// <param name="args">Optional parameters for formatting the message.</param>
- /// <returns>The localized error message.</returns>
- public static string GetMessage(ExceptionEnum code, string language = "en", params object[] args)
- {
- if (AppExceptions.ExceptionMessages.TryGetValue(code, out var translations)
- && translations.TryGetValue(language, out var message))
- {
- try
- {
- return string.Format(CultureInfo.InvariantCulture, message, args);
- }
- catch (FormatException)
- {
- return language == "ar" ? "فشل في تنسيق الرسالة." : "Message formatting failed.";
- }
- }
- // Default fallback
- return language == "ar" ? "رسالة الخطأ غير موجودة." : "Error message not found.";
- }
- public override string ToString()
- {
- return $"{base.ToString()}\nError Number: {ErrorNumber}\nError Message: {ErrorMessage}";
- }
- }
- }
|