Throw an exception if a template ID does not exist in your request body
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
I'll work on this
Any progress so far? Would also need an endpoint like that.
@Hantsch Not yet. Pull requests and +1s on the issue summary will help it move up the backlog.
@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?
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.