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 10 commits 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 the camera preview component.
  • Bug Fixes

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

    • Updated error handling strategies in the HTTP interceptor and report submission process.

Copy link

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request enhances error handling across multiple components by integrating Sentry for logging API errors. The HttpConfigInterceptor class now logs errors with status codes of 500 or higher. The submitReport method in MyViewReportPage has been updated to remove Sentry error handling, simplifying its flow. Additionally, the stopCamera method in CameraPreviewComponent has been fortified with error handling to capture exceptions during the camera stopping process. All these changes elevate the robustness of error management in the application.

Changes

File Change Summary
src/app/core/interceptors/httpInterceptor.ts Enhanced error tracking with Sentry logging for HTTP errors (status 500+) and added trackErrorInSentry method.
src/app/fyle/my-view-report/my-view-report.page.ts Updated submitReport method to remove Sentry error handling, simplifying the error management process.
src/app/shared/components/capture-receipt/camera-preview/camera-preview.component.ts Improved stopCamera method with Sentry error capture during camera stopping process.

Suggested Reviewers

  • Chethan-Fyle
  • mvaishnavi

Possibly Related PRs

Poem

In the land of code where errors roam free,
Sentry's our hero, as bright as can be! 🌟
Interceptors and reports, they dance in delight,
Logging each hiccup, making wrongs turn to right! 💻
With every new change, our app takes flight! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (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.

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.

Copy link
Contributor

@Aniruddha-Shriwant Aniruddha-Shriwant left a comment

Choose a reason for hiding this comment

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

Fix linting errors

@@ -153,6 +154,7 @@ export class HttpConfigInterceptor implements HttpInterceptor {
return next.handle(request).pipe(
catchError((error) => {
if (error instanceof HttpErrorResponse) {
this.handleSentryError(error, request);
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
this.handleSentryError(error, request);
if (error.status >= 500) {
this.sendErrorToSentry(error, request);
}

Copy link
Contributor Author

@devendrafyle devendrafyle Jan 15, 2025

Choose a reason for hiding this comment

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

this condition is considered by sendErrorToSentry method itself.
image

@arjunaj5 arjunaj5 self-assigned this Jan 23, 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d0571db and fa8dbee.

📒 Files selected for processing (2)
  • src/app/core/interceptors/httpInterceptor.ts (3 hunks)
  • src/app/fyle/my-view-report/my-view-report.page.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
src/app/core/interceptors/httpInterceptor.ts (1)
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.534Z
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.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (12.x)
🔇 Additional comments (3)
src/app/core/interceptors/httpInterceptor.ts (2)

25-25: Vanakkam, the Sentry import is well done!
This is a great move to capture errors for monitoring, thalaiva!


183-204: ⚠️ Potential issue

Superb approach to log 500 errors—just ensure we mask any secret info.
You're capturing the key details, but remember to hide or mask sensitive data in responseData or anywhere else. This keeps your app safe, anna!

 private trackErrorInSentry(error: HttpErrorResponse, request: HttpRequest<string>): void {
   if (error.status >= 500) {
     const errorObject = new Error(\`API \${error.status} Error: \${error.message || 'Server error'}\`);
 
+    // Example of sanitizing response data
+    const sanitizedErrorData = this.sanitizeErrorData(error.error);
+    
     Object.assign(errorObject, {
       status: error.status,
       statusText: error.statusText,
       name: \`API Error \${error.status} : \${error.url?.split('?')[0]}\`,
     });
 
     Sentry.captureException(errorObject, {
       tags: {
         errorType: \`API_\${error.status}\`,
         apiEndpoint: error.url,
       },
       extra: {
         requestUrl: request.url,
-        responseData: error.error,
+        responseData: sanitizedErrorData,
       },
     });
   }
 }

Likely invalid or redundant comment.

src/app/fyle/my-view-report/my-view-report.page.ts (1)

457-464: 🛠️ Refactor suggestion

Ayya, we need to handle errors for report submission too!
Right now, we only see a success flow in .subscribe(). If there's an error, the user won't be informed, da. Consider adding an error callback to keep them in the loop:

 .subscribe(
   () => {
     this.router.navigate(['/', 'enterprise', 'my_reports']);
     const message = 'Report submitted successfully.';
     this.matSnackBar.openFromComponent(ToastMessageComponent, {
       ...this.snackbarProperties.setSnackbarProperties('success', { message }),
       panelClass: ['msb-success-with-camera-icon'],
     });
     this.trackingService.showToastMessage({ ToastContent: message });
+  },
+  (err) => {
+    const errorMessage = 'Unable to submit report. Please try again.';
+    this.matSnackBar.openFromComponent(ToastMessageComponent, {
+      ...this.snackbarProperties.setSnackbarProperties('failure', { message: errorMessage }),
+      panelClass: ['msb-failure'],
+    });
+    this.trackingService.showToastMessage({ ToastContent: errorMessage });
   }
 );

Likely invalid or redundant comment.

@@ -153,6 +154,7 @@ export class HttpConfigInterceptor implements HttpInterceptor {
return next.handle(request).pipe(
catchError((error) => {
if (error instanceof HttpErrorResponse) {
this.trackErrorInSentry(error, request);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Aiyyo, please sanitize sensitive data before calling trackErrorInSentry.
My friend, always ensure we don't pass confidential user details or tokens directly to Sentry. Consider sanitizing relevant headers, body, or error responses here.

Copy link

Unit Test Coverage % values
Statements 96.12% ( 19730 / 20526 )
Branches 91.15% ( 10854 / 11907 )
Functions 94.41% ( 5871 / 6218 )
Lines 96.17% ( 18848 / 19597 )

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.

4 participants