ترک استفاده از Try-Catch در همهجا: راهی هوشمندانهتر برای مدیریت خطاها
نویسنده: وحید نصیری
تاریخ: ۱۴۰۴/۰۱/۰۷ ۰۸:۰۴
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public string ReadFile(string path)
{
try
{
return File.ReadAllText(path);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return null;
}
}public string ReadFile(string path)
{
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
Console.WriteLine("مسیر فایل نامعتبر است یا فایل وجود ندارد.");
return null;
}
return File.ReadAllText(path);
}public class Result<T>
{
public bool IsSuccess { get; }
public T Value { get; }
public string Error { get; }
private Result(bool isSuccess, T value, string error)
{
IsSuccess = isSuccess;
Value = value;
Error = error;
}
public static Result<T> Success(T value) => new(true, value, null);
public static Result<T> Failure(string error) => new(false, default, error);
}
public Result<string> ReadFileSafe(string path)
{
if (!File.Exists(path))
{
return Result<string>.Failure("فایل یافت نشد.");
}
return Result<string>.Success(File.ReadAllText(path));
}public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception ex)
{
context.Response.StatusCode = 500;
return context.Response.WriteAsync("خطایی در سرور رخ داد: " + ex.Message);
}
}public async Task<string> GetApiData(string url)
{
try
{
using var client = new HttpClient();
return await client.GetStringAsync(url);
}
catch (HttpRequestException ex)
{
Console.WriteLine("خطا در ارتباط با API: " + ex.Message);
return null;
}
}static void Main()
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += (sender, e)
=> Infrastructure.GlobalExceptionHandler.Handle(e.Exception);
AppDomain.CurrentDomain.UnhandledException += (sender, e)
=> Infrastructure.GlobalExceptionHandler.Handle(e.ExceptionObject as Exception);
ApplicationConfiguration.Initialize();
Application.Run(new Forms.frmSplash());
}internal static class GlobalExceptionHandler
{
public static void Handle(Exception? ex)
{
if (ex == null) return;
if (!System.IO.Directory.Exists("Logs"))
System.IO.Directory.CreateDirectory("Logs");
var logPath = $"Logs\\{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day} Error_Log.txt";
// Log the error (e.g., write to a file, database, or logging service)
File.AppendAllText(logPath, $"\n------------------------------------------\n{DateTime.Now}: {ex}");
// Show a user-friendly message
MessageBox.Show("An unexpected error occurred. Please restart the application.",
"Application Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}