Skip to content

fix(java): report custom codec read failures as ForyJsonException - #4228

Open
pavel-ptashyts wants to merge 1 commit into
apache:mainfrom
pavel-ptashyts:json-codec-exception-wrap
Open

pavel-ptashyts wants to merge 1 commit into
apache:mainfrom
pavel-ptashyts:json-codec-exception-wrap

Conversation

@pavel-ptashyts

@pavel-ptashyts pavel-ptashyts commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Why?

An unchecked exception thrown by a custom codec while ForyJson.fromJson reads a value reaches
the caller with its own type, for example a raw NumberFormatException or an exception from a
third-party parser the codec delegates to. Other application code that Fory JSON invokes during a
read (@JsonAnySetter, @JsonCreator, @JsonValidator) is already reported as
ForyJsonException with the original cause, and built-in scalar codecs convert JDK parser failures
the same way. Callers that turn malformed input into a client error by catching ForyException
therefore miss codec failures and answer with a server error instead. Details in #4227.

What does this PR do?

  • Root read wrap. The six private root read helpers in ForyJson (Latin1, UTF-16 and UTF-8,
    each for Class and TypeRef roots) put one try/catch around the root value read. A
    RuntimeException that is not a ForyException becomes
    ForyJsonException("Cannot read JSON value at JSON position N: <cause>", cause). Every fromJson
    overload goes through these helpers, including InputStream, byte ranges and
    JsonStreamDecoder frames.
  • Unchanged. ForyException subclasses (including a codec's own ForyJsonException) and
    Errors propagate as before. Root type resolution, argument validation and the root result cast
    stay outside the try. Write paths and the token-level readUtf8(..., Function) /
    writeUtf8(Consumer) operations keep their documented "unchecked exceptions propagate unchanged"
    contract, because there the operation is the caller's own code.
  • No per-value cost. Codec, property, collection and generated read paths are untouched; the
    only change on the success path is an exception-table entry in each root helper. The failure
    message is built in a separate cold static method.
  • Docs. ForyJsonException Javadoc (it previously said user exceptions "may retain their own
    type") and docs/json/custom-codecs.md.
  • Tests. JsonCodecAnnotationTest#codecFailure, in both codegen modes: a throwing
    AbstractJsonValueCodec as the root value and as a property, through String (ASCII Latin1,
    non-ASCII Latin1 and UTF-16), byte[], byte range, InputStream and TypeRef roots; the
    property case asserts the generated codec is used when codegen is on. It also checks that a
    codec's own ForyJsonException and an Error propagate as the same instance. The test fails on
    apache/main with the raw NumberFormatException.

Kept by decision:

  • Write side not wrapped. toJson failures come from the application's own values, not from
    untrusted input, so they do not affect how callers classify malformed requests. Happy to extend
    the same rule to writes if maintainers prefer symmetry.
  • No property path in the message. Only the root knows about the failure, and tracking a path
    would need per-property work on the hot path. The JSON position is available for free.

Related issues

AI Contribution Checklist

  • Substantial AI assistance was used in this PR: yes
  • If yes, I included a completed AI Contribution Checklist in this PR description and the required AI Usage Disclosure.
  • If yes, my PR description includes the required ai_review summary and screenshot evidence or equivalent persisted links of the final clean AI review results from both fresh reviewers described in AI_POLICY.md, the Fory-guided reviewer and the independent general reviewer, on the current PR diff or current HEAD after the latest code changes.

Completed checklist from AI_POLICY.md section 9:

  • Substantial AI assistance was used in this PR: yes
  • I included the standardized AI Usage Disclosure block below.
  • I can explain and defend all important changes without AI help.
  • I reviewed AI-assisted code changes line by line before submission.
  • I completed line-by-line self-review first and fixed issues before requesting AI review.
  • I ran two fresh AI review agents on the current PR diff or current HEAD after the latest code changes: one Fory-guided reviewer using AGENTS.md and .agents/ci-and-pr.md, and one independent general reviewer in a separate clean-context review session that was not pointed to .agents/ci-and-pr.md or any copied Fory-specific review checklist.
  • I addressed all AI review comments and repeated the review loop until both ai reviewers reported no further actionable comments.
  • I attached equivalent persisted links of the final clean AI review results from both fresh reviewers on the current PR head in this PR body.
  • I ran adequate human verification and recorded evidence (checks run locally, pass/fail summary, and confirmation I reviewed results).
  • I added/updated tests and specs where required.
  • I validated protocol/performance impacts with evidence when applicable.
  • I verified licensing and provenance compliance.
AI Usage Disclosure
- substantial_ai_assistance: yes
- scope: design drafting, code drafting, tests, docs, PR text
- affected_files_or_subsystems: java/fory-json (ForyJson root read helpers, ForyJsonException Javadoc, JsonCodecAnnotationTest), docs/json/custom-codecs.md
- ai_review: line-by-line self-review by the contributor is pending (see unchecked items above). Two fresh reviewers (Fory-guided and independent) on the current head; both reported no actionable comments in the first round, so no code changed from review.
- ai_review_artifacts: Fory-guided reviewer: https://github.com/apache/fory/pull/4228#issuecomment-6951181239 ; independent general reviewer: https://github.com/apache/fory/pull/4228#issuecomment-6951182148 (both on head e352ce11, final round, no further actionable comments)
- human_verification: see "Verification" below
- performance_verification: no per-value, codec or generated path changed; the root helpers gain one exception-table entry and a cold failure method
- provenance_license_confirmation: all code written for this PR against the Apache Fory sources; no third-party code introduced

Verification

JDK 21.0.2, Windows 11 x86_64, base apache/main c8bb610:

  • java/: mvn -pl fory-json spotless:check checkstyle:check: clean.
  • java/: mvn -pl fory-json test: 1335 tests, 0 failures except
    JsonGuavaOptionalDependencyTest.buildWithoutGuava, which could not start its child JVM on the
    test machine (os::commit_memory ... paging file is too small); rerun alone once memory was available: 2 tests (both codegen modes), 0 failures.
  • JsonCodecAnnotationTest#codecFailure fails on apache/main (raw NumberFormatException) and
    passes with the change, in both codegen modes.
  • docs/json/custom-codecs.md: prettier clean.

Does this PR introduce any user-facing change?

  • Does this PR introduce any public API change? No new API. fromJson now reports unchecked
    custom-codec failures as ForyJsonException with the original exception as the cause.
  • Does this PR introduce any binary protocol compatibility change?

An unchecked exception thrown by a custom codec while fromJson reads a value
escaped the root operation with its own type, unlike failures of other
application code invoked during a read (any-setters, creators, validators),
which are already reported as ForyJsonException. Callers that handle
malformed input by catching ForyException then saw a raw
NumberFormatException or a third-party parser exception.

Wrap non-Fory runtime exceptions once around the root value read on the
Latin1, UTF-16 and UTF-8 paths, keeping the original exception as the cause
and naming the JSON position. ForyException subclasses and Errors propagate
unchanged; codec, property and generated read paths get no per-value
exception handling. Write paths and the readUtf8/writeUtf8 token operations
keep propagating application exceptions unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pavel-ptashyts

Copy link
Copy Markdown
Contributor Author

AI review artifact: Fory-guided reviewer (final round)

  • Reviewer: Codex CLI codex exec, model gpt-6-astra, reasoning effort medium, read-only sandbox, fresh session
  • Instructions: Fory-guided reviewer per AI_POLICY.md, following AGENTS.md and .agents/ci-and-pr.md
  • Reviewed: git diff apache/main...HEAD at head e352ce11 (base c8bb6101)
  • Result:
No further actionable comments.

@pavel-ptashyts

Copy link
Copy Markdown
Contributor Author

AI review artifact: independent general reviewer (final round)

  • Reviewer: Claude Code CLI claude -p, model claude-opus-5-5, effort medium, read-only tools (Read Grep Glob), no MCP, fresh session
  • Instructions: independent general reviewer per AI_POLICY.md; not pointed to .agents/ci-and-pr.md or any Fory review checklist (AGENTS.md independent-review carve-out)
  • Reviewed: git diff apache/main...HEAD at head e352ce11 (base c8bb6101)
  • Result:
No further actionable comments.

This branch has not been deployed

No deployments
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.

[Java] Fory JSON: runtime exceptions from custom codecs escape fromJson unwrapped

1 participant