SendGrid 有效,但仍然抛出在 catch() 块中无法捕获的异常

SendGrid works, but still throws exception not catchable in catch() block

注意:对于错误关闭此问题的版主,它与通用 nullref 问题完全不同。这是特定于 SendGrid.

我相信我已经非常接近 documented SendGrid usage:

public async Task<string> SendEmailSendGrid(string emailTo, string subject, string body) {
  var apiKey = SafeTrim(ConfigurationManager.AppSettings["SendGridAPIKey"]);
  var client = new SendGridClient(apiKey);
  var from = new EmailAddress(SafeTrim(ConfigurationManager.AppSettings["SendGridEmail"]));
  var to = new EmailAddress(emailTo);
  var msg = MailHelper.CreateSingleEmail(from, to, subject, string.Empty, body);

  try {
    var response = await client.SendEmailAsync(msg);
    //return response;
    return "SUCCESS";
  } catch (Exception ex) {
    return "ERROR in SendEmailSendGrid(): " + ex.Message;
  }
}

来电者:

var result = utils.SendEmailSendGrid(decodedEmail, "email test", "This is a test email using SendGrid.");

我每次都收到错误 即使它有效 并且电子邮件实际发送并到达我的收件箱:

Object reference not set to an instance of an object.

错误发生在这一行:

var response = await client.SendEmailAsync(msg);

我确认我的所有变量都按预期填充 - none 为 null 或空。我将一个空字符串传递给纯文本参数(因为我总是想要 HTML 内容),但我也尝试传递一些内容,但没有任何区别;同样的错误。

一件奇怪的事:它爆炸得如此厉害,以至于我的 catch 区块从未进入过。相反,一旦抛出异常,这个全屏 window 就会出现在我的 VS2022:

所以它正在工作并发送电子邮件,但为什么严重崩溃?我做错了什么?

等待方法:

public async Task<string> SendEmailSendGrid(...

然而,调用方并未等待结果:

var result = utils.SendEmailSendGrid(decodedEmail, ...

要么等待结果:

var result = await utils.SendEmailSendGrid(decodedEmail, ...

或者,如果调用方法不是 async 方法:

var result = utils.SendEmailSendGrid(decodedEmail, ...).GetAwaiter().GetResult();

Visual Studio 没有破坏您的 try/catch b/c 异常是在 .NET 框架中,不等待结果。您应该能够通过在 visual studio 调试器设置 (IIRC) 中启用“仅我的代码”来解决该问题。