Search code examples
c#.netsendgridsendgrid-api-v3

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


Note: To the moderator that incorrectly closed this question, it's completely different from the generic nullref question. This is specific to SendGrid.

I believe I'm following pretty close to 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;
  }
}

And the caller:

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

And the error I get every time EVEN THOUGH IT WORKS and the email actually sends and arrives in my inbox:

Object reference not set to an instance of an object.

That error occurs on this line:

var response = await client.SendEmailAsync(msg);

I verified that all my variables are populated as expected - none are null or empty. I am passing an empty string to the plain text param (because I always want HTML contents), but I also tried passing that some content and it made no difference; same error.

A strange thing: this blows up so hard that my catch block is never entered. Instead, as soon as the exception is thrown, this full-screen window comes up in my VS2022:

enter image description here

So it is working and sending the email, but why the heavy crash? What am I doing wrong?


Solution

  • The method is awaitable:

    public async Task<string> SendEmailSendGrid(...
    

    Yet, the caller is not awaiting the result:

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

    Either await the result:

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

    Or, if the invoking method is not an async method:

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

    Visual Studio is not breaking inside of your try/catch b/c the exception is in the .NET framework by not awaiting the result. You should be able to resolve that by enabling "just my code" in the visual studio debugger settings (IIRC).