Skip to content

Better error handling for failed emails #1540

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 10, 2024
Merged

Conversation

matt-aitken
Copy link
Member

@matt-aitken matt-aitken commented Dec 8, 2024

If we got an email back from our email provider we weren't propagating that error back up, causing a retry. Their SDK changed to not throw errors at some point.

Summary by CodeRabbit

  • New Features

    • Introduced a custom error handling mechanism for email sending operations.
    • Added a new EmailError class to enhance error clarity.
  • Bug Fixes

    • Improved error handling during email sending to prevent unhandled exceptions.

Copy link
Contributor

coderabbitai bot commented Dec 8, 2024

Caution

Review failed

The pull request is closed.

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

internal-packages/emails/src/index.tsx

Oops! Something went wrong! :(

ESLint: 8.45.0

ESLint couldn't find the config "custom" to extend from. Please check that the name of the config is correct.

The config "custom" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The changes in this pull request focus on enhancing error handling within the EmailClient class located in internal-packages/emails/src/index.tsx. A new mechanism is introduced in the #sendEmail method to capture and process errors during the email sending operation. Additionally, a custom error class, EmailError, is created to provide more informative error messages. The modifications do not alter any public or exported entity signatures, maintaining the existing structure of the class.

Changes

File Path Change Summary
internal-packages/emails/src/index.tsx - Updated #sendEmail method to include error handling.
- Introduced EmailError class extending the built-in Error class for better error management.

Possibly related PRs

  • Pass init output to all error handlers #1441: This PR enhances error handling by adding a new property to the HandleErrorArgs type, which aligns with the main PR's focus on improving error handling in the EmailClient class. Both PRs aim to refine how errors are managed within their respective contexts.

Poem

In the land of emails, swift and bright,
A new error handler brings delight.
With EmailError to guide the way,
No more lost messages in dismay.
Hopping through code, we cheer and play! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c5b69eb and 7d6db03.

📒 Files selected for processing (1)
  • internal-packages/emails/src/index.tsx (2 hunks)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
internal-packages/emails/src/index.tsx (2)

130-144: LGTM! Consider enhancing error logging

The new error handling implementation properly captures and propagates email provider errors, which addresses the PR objective.

Consider enhancing the error logging to include more context:

-        console.error(
-          `Failed to send email to ${to}, ${subject}. Error ${result.error.name}: ${result.error.message}`
-        );
+        console.error(
+          `Failed to send email to ${to}, subject: "${subject}". ` +
+          `Provider error [${result.error.name}]: ${result.error.message}`,
+          { error: result.error }
+        );

158-164: Add documentation and type safety to EmailError class

The EmailError class implementation is correct, but could benefit from better documentation and type safety.

Consider these improvements:

+/** Known error names from the email provider */
+type EmailErrorName = 
+  | "rate_limit_exceeded"
+  | "invalid_recipient"
+  | "delivery_error"
+  | string;
+
+/**
+ * Custom error class for email-related errors
+ * @extends Error
+ */
 export class EmailError extends Error {
+  name: EmailErrorName;
+
   constructor({ name, message }: { name: string; message: string }) {
     super(message);
     this.name = name;
   }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2a07ea4 and c5b69eb.

📒 Files selected for processing (1)
  • internal-packages/emails/src/index.tsx (2 hunks)

Comment on lines +130 to +144
const result = await this.#client.emails.send({
from: this.#from,
to,
reply_to: this.#replyTo,
subject,
react,
});

if (result.error) {
console.error(
`Failed to send email to ${to}, ${subject}. Error ${result.error.name}: ${result.error.message}`
);
throw new EmailError(result.error);
}

Copy link
Contributor

@coderabbitai coderabbitai bot Dec 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Based on the gathered information, I can now provide a final response:

EmailError handling needs to be added to webapp email service

The new EmailError is thrown in the email package but the webapp's email service (apps/webapp/app/services/email.server.ts) doesn't handle it specifically:

  • sendEmail and sendAlertEmail functions directly return the client calls without error handling
  • Only sendMagicLinkEmail has a try-catch block, but it catches and rethrows generic errors
  • sendPlainTextEmail has no error handling

Add specific EmailError handling to these functions to maintain consistent error handling across the codebase.

🔗 Analysis chain

Verify error handling in calling code

Let's ensure that all callers of #sendEmail are prepared to handle the new EmailError type.

Also applies to: 158-164

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct calls to send() method and verify error handling
rg -l "emailClient\.send\(" | while read -r file; do
  echo "=== Checking $file ==="
  # Show the context around send() calls to verify error handling
  rg -B 2 -A 4 "emailClient\.send\(" "$file"
done

# Search for any existing try-catch blocks that might need updating
rg "catch.*EmailError" 

Length of output: 69


Script:

#!/bin/bash
# Let's try a different approach to find email sending patterns and error handling

# First, let's find all files that might contain email-related code
echo "=== Files containing email-related code ==="
rg -l -i "email" 

# Look for method calls on any email client/service
echo -e "\n=== Email sending patterns ==="
rg -A 3 -B 3 "\.send\(" 

# Look for error handling patterns around email
echo -e "\n=== Error handling patterns ==="
rg -A 3 -B 3 "try.*{.*send"

# Check for any existing EmailError references
echo -e "\n=== EmailError usage ==="
rg -l "EmailError"

Length of output: 49183


Script:

#!/bin/bash
# Let's find all places where the email client is used and check error handling
echo "=== Files importing or using the email client ==="
rg -l "from.*['\"]@trigger\.dev/emails['\"]|from.*['\"]internal-packages/emails['\"]"

# Let's check the implementation and usage of EmailError
echo -e "\n=== EmailError implementation and usage ==="
rg -A 5 -B 5 "class.*EmailError|new EmailError"

# Let's look for try-catch blocks around email sending
echo -e "\n=== Error handling around email sending ==="
rg -A 5 -B 5 "try.*{.*#sendEmail|try.*{.*emailClient\.send"

Length of output: 1988


Script:

#!/bin/bash
# Let's try a different approach to find error handling patterns
echo "=== Error handling patterns around email sending ==="
rg -A 5 -B 5 "try\s+{[\s\S]*?sendEmail|try\s+{[\s\S]*?emails\.send"

# Let's find all files that use the email client
echo -e "\n=== Files using email client ==="
rg -l "new EmailClient|EmailClient\(" 

# Let's check for any imports of the email module
echo -e "\n=== Email module imports ==="
rg -l "from ['\"](\.\.\/)*emails['\"]|require\(['\"].*emails['\"]"

Length of output: 773


Script:

#!/bin/bash
# Let's examine the email client usage in the webapp
echo "=== Email client implementation in webapp ==="
cat "apps/webapp/app/services/email.server.ts"

# Let's look for try-catch blocks with simpler pattern
echo -e "\n=== Error handling patterns ==="
rg -A 5 -B 5 "try.*{.*send"

# Let's check for any email-related error handling
echo -e "\n=== Email error handling ==="
rg -A 5 -B 5 "catch.*{.*email"

Length of output: 3139

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@matt-aitken is this true?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but those functions are only called by Graphile jobs, so don't we want to throw so the jobs get retried.

sendEmail:

await sendEmail(payload);

sendAlertEmail is called in DeliverAlertService which is called from here:

const service = new DeliverAlertService();

@ericallam ericallam force-pushed the email-error-handling branch from c5b69eb to 7d6db03 Compare December 10, 2024 12:37
Copy link

changeset-bot bot commented Dec 10, 2024

⚠️ No Changeset found

Latest commit: 7d6db03

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@ericallam ericallam merged commit ea23dbd into main Dec 10, 2024
0 of 7 checks passed
@ericallam ericallam deleted the email-error-handling branch December 10, 2024 12:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants