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

Improve Boilerplate exception handling (#9635) #9636

Merged
merged 2 commits into from
Jan 8, 2025

Conversation

ysmoradi
Copy link
Member

@ysmoradi ysmoradi commented Jan 7, 2025

closes #9635

Summary by CodeRabbit

  • New Features

    • Added a new Default option to exception display handling
    • Enhanced exception handling with dynamic display kind selection
  • Bug Fixes

    • Improved error handling for token refresh and server connection scenarios
    • Gracefully manages exceptions during network-related operations
  • Refactor

    • Simplified exception handling logic across multiple components
    • Updated default exception display behavior

@ysmoradi ysmoradi requested a review from msynk January 7, 2025 19:36
Copy link

coderabbitai bot commented Jan 7, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces modifications to the exception handling mechanism across multiple client-side service files. The changes primarily focus on enhancing the flexibility of exception display and handling, particularly for scenarios involving server connection and token refresh issues. A new Default enum value is added to ExceptionDisplayKind, and the exception handling logic is updated to dynamically determine how exceptions are displayed based on their type.

Changes

File Change Summary
.../AppComponentBase.cs Modified exception handling to use ExceptionDisplayKind.Default
.../IClientCoreServiceCollectionExtensions.cs Added try-catch block for authManager.RefreshToken to handle ServerConnectionException
.../AuthManager.cs Simplified exception handling method call by removing displayKind parameter
.../ClientExceptionHandlerBase.cs Added GetDisplayKind method to dynamically determine exception display behavior
.../IExceptionHandler.cs Added new Default enum value and changed default display kind
.../ExceptionDelegatingHandler.cs Reformatted catch clause for improved readability

Assessment against linked issues

Objective Addressed Explanation
Handle ServerConnectionException during token refresh
Prevent disruption during frequent disconnections

Poem

🐰 A rabbit's tale of code so bright,
Exception handling, now just right!
Tokens refresh without a fright,
Connection issues lose their might,
Smooth sailing in the dev's delight! 🌟


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.

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: 0

🧹 Nitpick comments (4)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ClientExceptionHandlerBase.cs (1)

72-78: Consider expanding exception type handling.

The GetDisplayKind method currently handles specific exceptions. Consider making this method protected virtual to allow derived classes to customize the display kind for additional exception types.

-    private ExceptionDisplayKind GetDisplayKind(Exception exception)
+    protected virtual ExceptionDisplayKind GetDisplayKind(Exception exception)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (2)

163-167: Consider enhancing the exception handling strategy.

While catching ServerConnectionException prevents annoying errors during frequent disconnections, the empty catch block might hide important issues. Consider:

  1. Adding debug logging to track these occurrences
  2. Implementing a circuit breaker pattern to temporarily stop refresh attempts after X failures
  3. Distinguishing between temporary network issues and permanent server problems

Here's a suggested implementation with logging and basic circuit breaking:

+ private static int _failedAttempts = 0;
+ private static DateTime _lastFailure = DateTime.MinValue;
+ private const int MAX_ATTEMPTS = 3;
+ private const int RESET_INTERVAL_MINUTES = 5;

  try
  {
+     if (_failedAttempts >= MAX_ATTEMPTS && DateTime.UtcNow.Subtract(_lastFailure).TotalMinutes < RESET_INTERVAL_MINUTES)
+     {
+         return null; // Circuit is open, skip refresh attempts
+     }
      return await authManager.RefreshToken(requestedBy: nameof(HubConnectionBuilder));
  }
  catch (ServerConnectionException ex)
  {
+     _failedAttempts++;
+     _lastFailure = DateTime.UtcNow;
+     logger.LogDebug(ex, "Token refresh failed due to server connection issue. Attempt {Attempt}", _failedAttempts);
  }

163-167: Improve inline comment clarity.

The current comment /* If client gets disconnected... */ could be more descriptive about the rationale behind this implementation choice.

Consider updating the comment to:

- /* If client gets disconnected and access token become expired, then this code will be called every few seconds and will show annoying error to the user.  */
+ /* Suppress connection errors during token refresh attempts to prevent frequent error messages when:
+  * 1. Client loses connection
+  * 2. Access token expires
+  * 3. SignalR attempts to reconnect (which triggers token refresh)
+  */
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/AuthManager.cs (1)

Line range hint 126-141: Consider maintaining consistent exception handling patterns.

While the code correctly handles token cleanup for critical failures, there's an inconsistency in exception handling patterns within the same file (compare with TryEnterElevatedAccessMode method which uses explicit displayKind).

Consider either:

  1. Consistently using the new default behavior throughout the file, or
  2. Explicitly specifying the display kind for clarity in security-critical operations:
 exceptionHandler.Handle(exp, parameters: new()
 {
     { "AdditionalData", "Refreshing access token failed." },
     { "RefreshTokenRequestedBy", requestedBy }
-});
+}, displayKind: exp is ReusedRefreshTokenException ? 
+    ExceptionDisplayKind.NonInterrupting : 
+    ExceptionDisplayKind.Default);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54350f6 and cfc97c2.

📒 Files selected for processing (6)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/AppComponentBase.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/AuthManager.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ClientExceptionHandlerBase.cs (3 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/Contracts/IExceptionHandler.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/ExceptionDelegatingHandler.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (7)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/Contracts/IExceptionHandler.cs (2)

18-22: LGTM! Well-documented enum extension.

The addition of the Default value with clear documentation improves the flexibility of exception handling by allowing automatic selection of display kind based on exception type.


28-28: LGTM! Consistent parameter update.

Changing the default parameter to ExceptionDisplayKind.Default aligns with the new dynamic exception handling approach.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ClientExceptionHandlerBase.cs (1)

53-57: LGTM! Clean implementation of dynamic display kind selection.

The conditional check ensures that the display kind is only determined dynamically when explicitly requested through Default.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/AppComponentBase.cs (1)

263-263: LGTM! Consistent use of default display kind.

The change aligns with the new dynamic exception handling approach, allowing the display kind to be determined based on the exception type.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/ExceptionDelegatingHandler.cs (1)

65-68: LGTM! Improved readability of catch conditions.

The addition of parentheses makes the complex catch conditions more readable without changing the logic.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (1)

163-167: Verify error handling consistency across the codebase.

The approach to handling ServerConnectionException here might need to be consistent with other parts of the application that perform token refresh operations.

Let's verify the error handling approach in other token refresh scenarios:

✅ Verification successful

Silent catch of ServerConnectionException is appropriate and consistent with codebase patterns

The current error handling approach is consistent with how connection-related errors are managed across the codebase. The silent catch is intentional and well-documented, preventing unnecessary error messages during disconnected states while other components (AuthManager, RetryHandler) maintain proper error handling and logging when needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other token refresh implementations and their error handling
rg -A 5 "RefreshToken|ServerConnectionException" --type cs

Length of output: 37956

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/AuthManager.cs (1)

128-128: Verify exception handling behavior for security-critical operations.

The removal of explicit displayKind parameter relies on the new default behavior. While this aligns with the broader refactoring, we should ensure it maintains appropriate user feedback for security-critical token refresh failures.

Let's verify the new behavior:

✅ Verification successful

The removal of explicit displayKind parameter aligns with codebase patterns.

The change follows the consistent exception handling pattern seen across the authentication flows, where default behavior is predominantly used. The security-critical nature of token refresh operations is preserved as the exception handling cleanup remains intact.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other exception handling patterns in the codebase
# to ensure consistent behavior for security operations

# Look for other Handle calls with explicit displayKind
rg "Handle.*displayKind:" -A 2

# Look for exception handler configuration
ast-grep --pattern 'class $_ : ClientExceptionHandlerBase {
  $$$
  GetDisplayKind($_) {
    $$$
  }
}'

Length of output: 690


Script:

#!/bin/bash
# Search for ClientExceptionHandlerBase implementation
ast-grep --pattern 'class $_ : ClientExceptionHandlerBase {
    $$$
}'

# Find security-critical operations and their exception handling
rg "RefreshToken|SignIn|SignOut|Authenticate" -A 2

# Look for Handle method calls without displayKind
rg "\.Handle\([^,]+\)" --type cs

Length of output: 67314

@msynk msynk merged commit 64f2b15 into bitfoundation:develop Jan 8, 2025
3 checks passed
@ysmoradi ysmoradi deleted the 9635 branch January 9, 2025 17:36
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.

SignalR ServerConnectionException issue if Refresh Token required while there is a server connection issue
2 participants