using System;
using System.Globalization;
namespace MTWorkHR.Core.Global
{
public class AppException : Exception
{
///
/// Gets the error number associated with this exception.
///
public readonly ExceptionEnum ErrorNumber;
///
/// Gets the formatted error message.
///
public string ErrorMessage { get; private set; } = string.Empty;
public AppException(string errorMessage) : base(errorMessage)
{
ErrorMessage = errorMessage;
}
///
/// Creates a new instance of using an error number, language, and optional format arguments.
///
/// The error number (enum) representing the exception type.
/// The language code (e.g., "en" or "ar").
/// Optional arguments to format the error message.
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();
}
///
/// Sets the exception message for the base exception class.
///
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
}
///
/// Retrieves the error message based on the provided error code and language.
///
/// The error number (enum).
/// The language code (default: "en").
/// Optional parameters for formatting the message.
/// The localized error message.
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}";
}
}
}