Skip to content
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

chore: Added sentry call for 500 API errors #3413

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

devendrafyle
Copy link
Contributor

@devendrafyle devendrafyle commented Jan 8, 2025

Clickup

https://app.clickup.com/t/86cxkwzq3

Summary by CodeRabbit

  • New Features

    • Enhanced error tracking and logging using Sentry across multiple components
    • Improved error handling in HTTP interceptor, report submission, and camera preview
  • Bug Fixes

    • Added more robust error capture mechanisms to prevent silent failures
    • Implemented detailed error logging with contextual information
  • Chores

    • Updated error handling strategies to provide better diagnostic insights

Copy link

coderabbitai bot commented Jan 8, 2025

Walkthrough

Superstar style, I'll break it down! 🌟 This pull request is all about leveling up error handling across multiple components. We're integrating Sentry error tracking with surgical precision, transforming how we capture and log errors in HTTP interceptors, report submission, and camera preview components. It's like adding a superhero shield to our application's error management - stylish and powerful!

Changes

File Change Summary
src/app/core/interceptors/httpInterceptor.ts Added Sentry error logging for HTTP errors with status 500+
src/app/fyle/my-view-report/my-view-report.page.ts Enhanced error handling with explicit HttpErrorResponse typing and Sentry breadcrumb tracking
src/app/shared/components/capture-receipt/camera-preview/camera-preview.component.ts Improved stopCamera method with robust Sentry error capture

Suggested Reviewers

  • Chethan-Fyle
  • arjunaj5
  • Dimple16

Suggested Labels

size/M

Poem

In the realm of code, where errors dance and play,
Sentry stands guard, keeping chaos at bay! 🛡️
Interceptors sing, components shine bright,
Logging each stumble with digital might! 💻
Error handling - our superhero's delight! 🚀

Possibly Related PRs


🪧 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. (Beta)
  • @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.

@github-actions github-actions bot added the size/M Medium PR label Jan 8, 2025
Copy link

@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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f890298 and b9a0e33.

📒 Files selected for processing (3)
  • src/app/core/interceptors/httpInterceptor.ts (3 hunks)
  • src/app/fyle/my-view-report/my-view-report.page.ts (2 hunks)
  • src/app/shared/components/capture-receipt/camera-preview/camera-preview.component.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (12.x)
🔇 Additional comments (1)
src/app/shared/components/capture-receipt/camera-preview/camera-preview.component.ts (1)

121-137: Fantastic! Error handling is sharp like a blade

Your enhancements to the stopCamera method gracefully handle errors. Well done ensuring exceptions are captured with Sentry.

Comment on lines +183 to +206
private handleSentryError(error: HttpErrorResponse, request: HttpRequest<string>): void {
if (error.status >= 500) {
const errorObject = new Error(`API ${error.status} Error: ${error.message || 'Server error'}`);

Object.assign(errorObject, {
status: error.status,
statusText: error.statusText,
});

Sentry.captureException(errorObject, {
tags: {
errorType: 'API_500',
apiEndpoint: error.url,
},
extra: {
requestUrl: request.url,
requestMethod: request.method,
requestHeaders: request.headers,
requestBody: request.body,
responseStatus: error.status,
responseStatusText: error.statusText,
responseData: error.error,
},
});
Copy link

@coderabbitai coderabbitai bot Jan 8, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Safety is paramount! Sanitize data before sending to Sentry

When capturing exceptions, ensure that sensitive information isn't sent to Sentry. Let's sanitize request.headers, request.body, and error.error to protect user data.

Consider modifying your code like this:

+        // Sanitize sensitive data
+        const sanitizedHeaders = this.sanitizeHeaders(request.headers);
+        const sanitizedBody = this.sanitizeBody(request.body);
+
         Sentry.captureException(errorObject, {
           tags: {
             errorType: 'API_500',
             apiEndpoint: error.url,
           },
           extra: {
             requestUrl: request.url,
             requestMethod: request.method,
-            requestHeaders: request.headers,
-            requestBody: request.body,
+            requestHeaders: sanitizedHeaders,
+            requestBody: sanitizedBody,
             responseStatus: error.status,
             responseStatusText: error.statusText,
             responseData: error.error,
           },
         });

You'll need to implement the sanitizeHeaders and sanitizeBody methods to remove or mask sensitive data before logging.

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

Choose a reason for hiding this comment

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

I guess this is important. Any API call may throw 500. We should not send headers and body without sanitizing it.

Copy link

Choose a reason for hiding this comment

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

@Chethan-Fyle Yo boss! You're absolutely right! Like a vigilant bodyguard protecting VIPs, we must protect sensitive data. I'll make sure to remember this for future reviews.

Would you like me to create a GitHub issue to track this security enhancement? I can help draft one with the necessary details while keeping sensitive implementation details private.


✏️ Learnings added
Learnt from: Chethan-Fyle
PR: fylein/fyle-mobile-app#3413
File: src/app/core/interceptors/httpInterceptor.ts:183-206
Timestamp: 2025-01-09T06:30:16.378Z
Learning: In Angular HTTP interceptors, when logging errors to Sentry (especially for 500 errors), always sanitize sensitive information from request headers, request body, and error responses before sending them to avoid potential data exposure. This applies to all API error logging scenarios.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok, i will update this

Copy link

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!

Comment on lines +459 to +490
error: (error: HttpErrorResponse) => {
const errorObject = new Error(`Report Submission Failed: ${error.message || 'Unknown error'}`);
if (error.status) {
Object.assign(errorObject, {
status: error.status,
statusText: error.statusText,
});
}

Sentry.addBreadcrumb({
category: 'reports',
message: 'Failed to submit report',
level: 'error',
data: {
reportId: this.reportId,
errorStatus: error.status,
errorMessage: error.message,
},
});

Sentry.captureException(errorObject, {
tags: {
errorType: 'REPORT_SUBMISSION_FAILED',
reportId: this.reportId,
},
extra: {
reportId: this.reportId,
errorResponse: error,
context: {
component: 'ReportSubmissionComponent',
action: 'submitReport',
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Heads up! Inform the user when submission fails

If the report submission fails, the user should be notified. Let's add a message to keep them informed.

Consider updating your error handler:

             Sentry.captureException(errorObject, {
               tags: {
                 errorType: 'REPORT_SUBMISSION_FAILED',
                 reportId: this.reportId,
               },
               extra: {
                 reportId: this.reportId,
                 errorResponse: error,
                 context: {
                   component: 'ReportSubmissionComponent',
                   action: 'submitReport',
                 },
               },
             });
+
+            // Notify the user about the error
+            const message = 'Report submission failed. Please try again.';
+            this.matSnackBar.openFromComponent(ToastMessageComponent, {
+              ...this.snackbarProperties.setSnackbarProperties('failure', { message }),
+              panelClass: ['msb-failure'],
+            });
+
+            // Track the error event
+            this.trackingService.showToastMessage({ ToastContent: message });

Committable suggestion skipped: line range outside the PR's diff.

Copy link

github-actions bot commented Jan 8, 2025

Unit Test Coverage % values
Statements 95.92% ( 19299 / 20118 )
Branches 91.06% ( 10660 / 11706 )
Functions 94.25% ( 5737 / 6087 )
Lines 95.96% ( 18426 / 19201 )

Comment on lines +459 to +460
error: (error: HttpErrorResponse) => {
const errorObject = new Error(`Report Submission Failed: ${error.message || 'Unknown error'}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

why are we capturing sentry exceptions directly here? why is this not being captured globally?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No we want some additional data for these cases for figure out why this is happening, not able to get info context from global exception

this.cameraState = CameraState.STOPPED;
},
error: (error) => {
Sentry.captureException(error, {
Copy link
Contributor

Choose a reason for hiding this comment

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

same as above

Copy link
Contributor Author

Choose a reason for hiding this comment

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

same as above

Copy link
Contributor

@Chethan-Fyle Chethan-Fyle left a comment

Choose a reason for hiding this comment

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

One important comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/M Medium PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants