用于发送网格发送电子邮件的 System.Net.Http.HttpRequestException

问题描述

在某些情况下,我们在调用 Sendgrid Send Email 函数时会遇到以下异常。 我们每天收到 50,000 封电子邮件中的 20 到 30 封例外。

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the Remote Server ---> System.Net.sockets.socketException: UnkNown error (0xffffffff)     
at System.Net.sockets.socket.BeginConnectEx(EndPoint remoteEP,Boolean flowContext,AsyncCallback callback,Object state)     
at System.Net.sockets.socket.UnsafeBeginConnect(EndPoint remoteEP,Object state)     
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket& socket,IPAddress& address,ConnectSocketState state,IAsyncResult asyncResult,Exception& exception)     --- End of inner exception stack trace ---     
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult,TransportContext& context)     
at System.Net.Http.httpclienthandler.GetRequestStreamCallback(IAsyncResult ar)     --- End of inner exception stack trace ---     
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     
at SendGrid.Helpers.Reliability.RetryDelegatingHandler.<SendAsync>d__4.MoveNext()  --- End of stack trace from prevIoUs location where exception was thrown ---     
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     
at SendGrid.BaseClient.<MakeRequest>d__20.MoveNext()  --- End of stack trace from prevIoUs location where exception was thrown ---     
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     
at SendGrid.BaseClient.<RequestAsync>d__21.MoveNext()  --- End of stack trace from prevIoUs location where exception was thrown ---     
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     
at SendGrid.BaseClient.<SendEmailAsync>d__22.MoveNext()  --- End of stack trace from prevIoUs location where exception was thrown ---     
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    

我发送电子邮件代码

var client = new SendGridClient("API Key");
var response = await client.SendEmailAsync(message);

任何人都可以帮助我如何添加更多验证以避免这种情况。

解决方法

到目前为止,重试逻辑确实对我有用。

catch (Exception ex)
{
    if (--retryMax == 0)
    {
        throw;
    }
    else
    {
        await Task.Delay(1000);
    }
    return null;
}