50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using ChatBot.Services.Interfaces;
|
|
|
|
namespace ChatBot.Services.ErrorHandlers
|
|
{
|
|
/// <summary>
|
|
/// Error handler for network-related errors
|
|
/// </summary>
|
|
public class NetworkErrorHandler : IErrorHandler
|
|
{
|
|
private readonly ILogger<NetworkErrorHandler> _logger;
|
|
|
|
public NetworkErrorHandler(ILogger<NetworkErrorHandler> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
|
|
public bool CanHandle(Exception exception)
|
|
{
|
|
return exception is HttpRequestException
|
|
|| exception is TaskCanceledException
|
|
|| exception.Message.Contains("timeout", StringComparison.OrdinalIgnoreCase)
|
|
|| exception.Message.Contains("connection", StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
public async Task<ErrorHandlingResult> HandleAsync(
|
|
Exception exception,
|
|
int attempt,
|
|
string currentModel,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
_logger.LogWarning(
|
|
exception,
|
|
"Network error on attempt {Attempt} for model {Model}",
|
|
attempt,
|
|
currentModel
|
|
);
|
|
|
|
// Apply exponential backoff for network errors
|
|
var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt - 1));
|
|
|
|
_logger.LogInformation("Waiting {Delay} before retry due to network error", delay);
|
|
|
|
await Task.Delay(delay, cancellationToken);
|
|
|
|
return ErrorHandlingResult.Retry();
|
|
}
|
|
}
|
|
}
|