sendgrid-csharp icon indicating copy to clipboard operation
sendgrid-csharp copied to clipboard

Throw an exception if a template ID does not exist in your request body

Open thinkingserious opened this issue 7 years ago • 5 comments

Issue Summary

You will not receive an error from the API is you send an email with the wrong template. Instead you will get a "Not Delivered" notice in your email activity feed. We want to make that experience better by throwing an exception in the code instead.

This issue is inspired by this.

Acceptance Criteria

  • Use the API to verfiy a template ID exists, if not, throw an exception
  • A new test is added that demonstrates that if you use a non-existent template, the code will throw an error

thinkingserious avatar Oct 06 '18 14:10 thinkingserious

I'll work on this

Jerrgree avatar Oct 06 '18 15:10 Jerrgree

Any progress so far? Would also need an endpoint like that.

Hantsch avatar Oct 16 '20 07:10 Hantsch

@Hantsch Not yet. Pull requests and +1s on the issue summary will help it move up the backlog.

childish-sambino avatar Oct 16 '20 13:10 childish-sambino

@Hantsch Not yet. Pull requests and +1s on the issue summary will help it move up the backlog.

Hey there, still no plans to this in near future?

bossbast1 avatar Jul 28 '21 16:07 bossbast1

If you are willing to use the StrongGrid C# library instead of SendGrid's own library, you could very easily validate if a given template exists before attempting to send an email. Your code would look something like this:

// Validate the templateId
var templateIsValid = false;
try
{
    var template = await client.Templates.GetAsync(templateId, null, cancellationToken).ConfigureAwait(false);
    templateIsValid = true;
}
catch (SendGridException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
    // In this context we can safely ignore 'NotFound' exceptions because
    // it simply means that the 'templateId' is not valid.
    templateIsValid = false;
}

if (templateIsValid)
{
    // Send email using a dynamic template
    await client.Mail.SendToSingleRecipientAsync(to, from, templateId, cancellationToken: cancellationToken).ConfigureAwait(false);
}
else
{
    // Fallback to sending email without a template
    await client.Mail.SendToSingleRecipientAsync(to, from, subject, html, text, cancellationToken: cancellationToken).ConfigureAwait(false);
}

Hopefully this helps.

Jericho avatar Aug 03 '21 18:08 Jericho