Skip to content

Exception is thrown when component failed to register #1374

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
Jun 3, 2025

Conversation

CrazyHZM
Copy link
Contributor

@CrazyHZM CrazyHZM commented May 26, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling during component registration to provide clearer feedback when registration fails, ensuring errors are reported immediately instead of failing silently.

@sofastack-cla sofastack-cla bot added question Further information is requested cla:yes size/XS labels May 26, 2025
Copy link

coderabbitai bot commented May 26, 2025

Walkthrough

The change updates the exception handling in the doRegister method of ComponentManagerImpl. Instead of returning null or only logging errors upon exceptions during component registration, the method now throws a ServiceRuntimeException with an error code, ensuring failures are explicitly propagated. Corresponding test methods were adjusted to catch and assert these exceptions explicitly.

Changes

File(s) Change Summary
sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/.../ComponentManagerImpl.java Modified doRegister to throw ServiceRuntimeException on errors instead of returning null or just logging.
sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/test/java/.../ComponentManagerImplTests.java Updated tests to catch ServiceRuntimeException explicitly and assert error codes and component states.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ComponentManagerImpl
    participant ComponentInfo

    Caller->>ComponentManagerImpl: doRegister(ci)
    ComponentManagerImpl->>ComponentInfo: register()
    alt register() succeeds
        ComponentManagerImpl->>ComponentManagerImpl: insert registry, resolve, activate
        alt all succeed
            ComponentManagerImpl-->>Caller: return ComponentInfo
        else exception during registry/resolve/activate
            ComponentManagerImpl->>ComponentManagerImpl: log error and call ci.exception()
            ComponentManagerImpl-->>Caller: throw ServiceRuntimeException
        end
    else register() throws Exception
        ComponentManagerImpl->>ComponentManagerImpl: log error
        ComponentManagerImpl-->>Caller: throw ServiceRuntimeException
    end
Loading

Poem

In the warren of code, exceptions now leap,
No more silent returns, no errors to keep.
With a hop and a bound, they’re caught in the light,
ServiceRuntimeException takes flight!
The bugs will now scurry, the failures can’t hide—
For every bad burrow, a clear bunny guide.
🐇


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f24ccb and 4bc2d92.

📒 Files selected for processing (2)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java (2 hunks)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/test/java/com/alipay/sofa/runtime/impl/ComponentManagerImplTests.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/test/java/com/alipay/sofa/runtime/impl/ComponentManagerImplTests.java
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (21)
  • GitHub Check: build (17)
  • GitHub Check: sca
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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: 1

🔭 Outside diff range comments (2)
sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java (2)

186-191: ⚠️ Potential issue

Include the original exception as the cause in ServiceRuntimeException.

The exception handling correctly propagates the registration failure, but the original exception t is not included as the cause. This results in loss of valuable debugging information like the stack trace.

Apply this diff to preserve the original exception:

         } catch (Throwable t) {
             LOGGER.error(ErrorCode.convert("01-03003", ci.getName()), t);
-            throw new ServiceRuntimeException(ErrorCode.convert("01-03003", ci.getName()));
+            throw new ServiceRuntimeException(ErrorCode.convert("01-03003", ci.getName()), t);
         }

176-191: 💡 Verification agent

🧩 Analysis chain

Verify callers can handle the new exception behavior.

This change modifies the behavior from silent failure to throwing exceptions. While this improves error propagation, it's a breaking change that could affect existing callers.

Run the following script to identify all callers of the affected methods:

Additionally, consider updating the method's JavaDoc to document this exception behavior.


🏁 Script executed:

#!/bin/bash
# Description: Find all callers of register() and registerAndGet() methods to verify they can handle exceptions

# Search for direct calls to register method
echo "=== Direct calls to register() ==="
rg -A 3 '\.register\(' --type java

# Search for direct calls to registerAndGet method  
echo -e "\n=== Direct calls to registerAndGet() ==="
rg -A 3 '\.registerAndGet\(' --type java

# Search for ComponentManager interface usage
echo -e "\n=== ComponentManager interface usage ==="
ast-grep --pattern 'ComponentManager $_ = $_'

Length of output: 37810


Document new exception behavior and review callers

Even though ServiceRuntimeException is unchecked, this change can break existing integrations by propagating errors that were previously swallowed. Please:

• Update the JavaDoc for both ComponentManager.register(...) and ComponentManager.registerAndGet(...) (and their implementations) to declare
@throws ServiceRuntimeException
and describe the conditions under which it’s thrown.
• Audit any high-level callers (e.g., Spring factories, service/client initializers) to decide whether they should

  1. Let the exception bubble up (fail fast), or
  2. Catch it and handle it gracefully.

Tags:

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c53e51c and ab1db35.

📒 Files selected for processing (1)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (21)
  • GitHub Check: build (17)
  • GitHub Check: sca

Comment on lines 209 to 213
} catch (Throwable t) {
ci.exception(new Exception(t));
LOGGER.error(ErrorCode.convert("01-03004", ci.getName()), t);
throw new ServiceRuntimeException(ErrorCode.convert("01-03004", ci.getName()));
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Include the original exception as the cause in ServiceRuntimeException.

Similar to the previous exception handling, the original exception t should be included as the cause to preserve debugging information.

Apply this diff to preserve the original exception:

         } catch (Throwable t) {
             ci.exception(new Exception(t));
             LOGGER.error(ErrorCode.convert("01-03004", ci.getName()), t);
-            throw new ServiceRuntimeException(ErrorCode.convert("01-03004", ci.getName()));
+            throw new ServiceRuntimeException(ErrorCode.convert("01-03004", ci.getName()), t);
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (Throwable t) {
ci.exception(new Exception(t));
LOGGER.error(ErrorCode.convert("01-03004", ci.getName()), t);
throw new ServiceRuntimeException(ErrorCode.convert("01-03004", ci.getName()));
}
} catch (Throwable t) {
ci.exception(new Exception(t));
LOGGER.error(ErrorCode.convert("01-03004", ci.getName()), t);
throw new ServiceRuntimeException(
ErrorCode.convert("01-03004", ci.getName()),
t
);
}
🤖 Prompt for AI Agents
In
sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java
around lines 209 to 213, the catch block creates a new ServiceRuntimeException
without passing the original Throwable `t` as the cause, which can hinder
debugging. Fix this by passing `t` as the cause when constructing the
ServiceRuntimeException, ensuring the original exception details are preserved
in the stack trace.

@CrazyHZM CrazyHZM force-pushed the 4.x_feat/component_failed branch from ab1db35 to 9f24ccb Compare June 3, 2025 04:03
@sofastack-cla sofastack-cla bot added size/M and removed size/XS labels Jun 3, 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: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab1db35 and 9f24ccb.

📒 Files selected for processing (2)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java (2 hunks)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/test/java/com/alipay/sofa/runtime/impl/ComponentManagerImplTests.java (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/impl/ComponentManagerImpl.java
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (17)
  • GitHub Check: build (21)
  • GitHub Check: sca
🔇 Additional comments (3)
sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/test/java/com/alipay/sofa/runtime/impl/ComponentManagerImplTests.java (3)

50-50: LGTM: OutputCaptureExtension added for test output validation.

The addition of OutputCaptureExtension.class to the @ExtendWith annotation is necessary for capturing console output in the updated test methods.


154-162: Clarify test expectations in resolveException method.

The test logic appears inconsistent. The assertion in the try block expects successful registration, but the catch block suggests a ServiceRuntimeException should be thrown. This creates ambiguity about what the test is actually validating.

Please clarify the expected behavior:

  • Should registration succeed but resolution fail and throw an exception?
  • Or should both registration and resolution fail with an exception?

If registration should succeed but resolution should fail, consider this refactor:

 try {
     assertThat(componentManager.registerAndGet(componentInfoA)).isEqualTo(componentInfoA);
-
+    // The exception should be thrown during resolution, not registration
+    componentManager.resolvePendingResolveComponent(componentInfoA.getName());
+    // Should not reach here if exception is thrown as expected
+    assertThat(false).as("Expected ServiceRuntimeException during resolution").isTrue();
 } catch (ServiceRuntimeException e) {
     assertThat(componentInfoA.isHealthy().isHealthy()).isFalse();
     assertThat(capturedOutput.getOut()).contains("01-03004");
     assertThat(capturedOutput.getOut()).contains(componentInfoA.getName().toString());
 }

58-66: LGTM: Formatting improvements enhance readability.

The line continuation formatting improvements throughout the file enhance code readability without changing functionality.

Also applies to: 73-73, 87-91, 100-105, 168-172, 189-193, 210-214, 229-229, 240-242

Comment on lines +141 to 147
try {
assertThat(componentManager.registerAndGet(componentInfoA)).isNull();
} catch (ServiceRuntimeException e) {
assertThat(capturedOutput.getOut()).contains("01-03003");
assertThat(capturedOutput.getOut()).contains(componentInfoA.getName().toString());
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent test logic in registerException method.

The test logic is inconsistent. If a ServiceRuntimeException is expected to be thrown (which it should be based on the PR objectives), then the assertion assertThat(componentManager.registerAndGet(componentInfoA)).isNull(); in the try block will never be executed and doesn't align with the exception-based behavior.

Apply this diff to fix the test logic:

 try {
-    assertThat(componentManager.registerAndGet(componentInfoA)).isNull();
+    componentManager.registerAndGet(componentInfoA);
+    // Should not reach here if exception is thrown as expected
+    assertThat(false).as("Expected ServiceRuntimeException to be thrown").isTrue();
 } catch (ServiceRuntimeException e) {
     assertThat(capturedOutput.getOut()).contains("01-03003");
     assertThat(capturedOutput.getOut()).contains(componentInfoA.getName().toString());
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
assertThat(componentManager.registerAndGet(componentInfoA)).isNull();
} catch (ServiceRuntimeException e) {
assertThat(capturedOutput.getOut()).contains("01-03003");
assertThat(capturedOutput.getOut()).contains(componentInfoA.getName().toString());
}
}
try {
componentManager.registerAndGet(componentInfoA);
// Should not reach here if exception is thrown as expected
assertThat(false).as("Expected ServiceRuntimeException to be thrown").isTrue();
} catch (ServiceRuntimeException e) {
assertThat(capturedOutput.getOut()).contains("01-03003");
assertThat(capturedOutput.getOut()).contains(componentInfoA.getName().toString());
}
}
🤖 Prompt for AI Agents
In
sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/test/java/com/alipay/sofa/runtime/impl/ComponentManagerImplTests.java
around lines 141 to 147, the test incorrectly asserts a null return inside a try
block where a ServiceRuntimeException is expected, causing inconsistent logic.
Remove the assertion inside the try block and instead directly invoke the method
expecting the exception, then catch the ServiceRuntimeException and perform
assertions on the captured output to verify the error message and component
name.

@CrazyHZM CrazyHZM force-pushed the 4.x_feat/component_failed branch from 9f24ccb to 4bc2d92 Compare June 3, 2025 06:50
@sofastack-cla sofastack-cla bot added size/S and removed size/M labels Jun 3, 2025
Copy link

codecov bot commented Jun 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.90%. Comparing base (c53e51c) to head (4bc2d92).
Report is 2 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1374      +/-   ##
============================================
- Coverage     82.91%   82.90%   -0.02%     
  Complexity     2971     2971              
============================================
  Files           340      340              
  Lines          9828     9833       +5     
  Branches       1178     1178              
============================================
+ Hits           8149     8152       +3     
  Misses         1164     1164              
- Partials        515      517       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@CrazyHZM CrazyHZM merged commit a116aaf into sofastack:master Jun 3, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cla:yes question Further information is requested size/S
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant