java-sdk icon indicating copy to clipboard operation
java-sdk copied to clipboard

feat: improve error messaging

Open SoulPancake opened this issue 2 weeks ago • 2 comments

Description

SDK errors currently only expose the operation name (e.g., "check") rather than the API's actual error message. This makes debugging difficult when errors occur.

Changes Added fields to FgaError:

apiErrorMessage - Parsed error message from API response body (null if unavailable) operationName - Operation that failed (e.g., "check", "write") Enhanced getError() parsing:

Sets apiErrorMessage when successfully parsed from response JSON Sets operationName for all errors Maintains existing fallback behavior (operation name) for empty/non-JSON responses Preserves backward compatibility:

getMessage() behavior unchanged - returns parsed message or operation name as before All existing tests pass without modification New fields are nullable and additive only

What problem is being solved?

How is it being solved?

What changes are made to solve it?

References

Review Checklist

  • [x] I have clicked on "allow edits by maintainers".
  • [x] I have added documentation for new/changed functionality in this PR or in a PR to openfga.dev [Provide a link to any relevant PRs in the references section above]
  • [x] The correct base branch is being used, if not main
  • [x] I have added tests to validate that the change in functionality is working as expected

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved error reporting with automatic parsing of API response details, including error codes, operation names, and request identifiers for enhanced troubleshooting and diagnostics.
  • Tests

    • Added comprehensive test suite covering error parsing, fallback behavior, and error metadata handling.

SoulPancake avatar Nov 11 '25 09:11 SoulPancake

[!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.

[!NOTE]

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

The PR enhances error handling in the SDK by introducing JSON parsing utilities to extract detailed error messages and codes from API response bodies. It enriches FgaError instances with API metadata (apiErrorMessage, apiErrorCode, operationName) and includes comprehensive test coverage for various error scenarios and fallback behaviors.

Changes

Cohort / File(s) Summary
Changelog Entry
CHANGELOG.md
Adds unreleased changelog entry describing improved error messaging through parsing error details from response bodies for issue #256.
Error Handling Enhancement
src/main/java/dev/openfga/sdk/errors/FgaError.java
Introduces parseErrorMessage and extractErrorCode JSON parsing utilities; adds centralized ERROR_MAPPER (ObjectMapper); extends FgaError with new fields (apiErrorMessage, operationName) and metadata getters/setters; enriches error construction with request ID, API error code, operation name, and retry-after header propagation; adds getCode() alias method.
Error Handling Tests
src/test/java/dev/openfga/sdk/errors/FgaErrorTest.java
Introduces comprehensive test suite covering error parsing for validation, internal, and not-found errors; tests fallback behavior for missing/invalid response bodies; validates request ID and metadata extraction; tests authentication and rate-limiting error mappings; includes helper methods for mocking HttpResponse objects.

Sequence Diagram

sequenceDiagram
    participant Client
    participant SDK as SDK<br/>(getError)
    participant Parser as JSON Parser<br/>(ERROR_MAPPER)
    participant Error as FgaError
    
    Client->>SDK: HTTP Response + Request metadata
    SDK->>SDK: Determine error type<br/>(status code)
    SDK->>Parser: Parse response body
    alt Parsing succeeds
        Parser-->>SDK: errorMessage, errorCode
    else Parsing fails
        Parser-->>SDK: defaults (empty/null)
    end
    SDK->>Error: Create error instance<br/>(type, errorMessage)
    SDK->>Error: Enrich with metadata<br/>(operationName, apiErrorCode,<br/>requestId, retryAfter)
    Error-->>Client: Return populated<br/>FgaError

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • JSON parsing logic: Review parseErrorMessage and extractErrorCode for proper null-safety, exception handling, and edge cases with malformed or missing response bodies.
  • Metadata enrichment in getError(): Verify that all fields are correctly populated from response and headers, and that the operation-name fallback logic works as intended.
  • Test coverage: Confirm that the test suite adequately covers parsing failures, missing data scenarios, and correct metadata propagation across different error types.
  • Backward compatibility: Ensure the updated getError signature change does not break existing callers, particularly regarding the addition of Configuration and HttpResponse<String> parameters.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.26% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: improve error messaging' directly aligns with the main change: enhancing SDK error reporting by improving how error messages are parsed and presented from API responses.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Nov 11 '25 09:11 coderabbitai[bot]

Codecov Report

:x: Patch coverage is 82.48175% with 24 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 37.46%. Comparing base (d93032f) to head (bf18849).

Files with missing lines Patch % Lines
.../dev/openfga/sdk/errors/FgaApiValidationError.java 77.77% 4 Missing and 8 partials :warning:
src/main/java/dev/openfga/sdk/errors/FgaError.java 85.54% 2 Missing and 10 partials :warning:
Additional details and impacted files
@@             Coverage Diff              @@
##               main     #258      +/-   ##
============================================
+ Coverage     36.47%   37.46%   +0.99%     
- Complexity     1144     1196      +52     
============================================
  Files           188      188              
  Lines          7192     7322     +130     
  Branches        824      854      +30     
============================================
+ Hits           2623     2743     +120     
+ Misses         4462     4456       -6     
- Partials        107      123      +16     

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

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

codecov-commenter avatar Nov 11 '25 09:11 codecov-commenter

Will Re-open a new one with less brittle json parsing

SoulPancake avatar Nov 18 '25 05:11 SoulPancake