Skip to content

Fix TryConvertTo<T> throwing exceptions in the TypeConverter fallback path - #67091

Merged
kotlarmilos merged 38 commits into
dotnet:mainfrom
irfanajaffer:1031580_BindConverter
Nov 24, 2026
Merged

kotlarmilos merged 38 commits into
dotnet:mainfrom
irfanajaffer:1031580_BindConverter

Conversation

@irfanajaffer

@irfanajaffer irfanajaffer commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Description:

BindConverter.TryConvertTo<T>() violates the Try* contract for any T whose conversion falls through to the TypeConverter path: on parse failure the TypeConverter.ConvertFrom exception escapes the call instead of being converted to false. This affects unsigned integer types (uint, ushort, ulong, byte), sbyte, char, and any user-defined or BCL type that is resolved via a TypeConverter (for example [TypeConverter]-attributed custom types).

This PR adds a try/catch around the TypeConverter.ConvertFrom call in MakeTypeConverterConverter<T>() so that any of the documented conversion-failure exceptions (NotSupportedException, FormatException, OverflowException, ArgumentException, JsonException) are converted to a false return, matching the behavior of the explicit TryParse-based parsers for the other primitive types and aligning with the Try* contract.

The narrow null-handling tweak that was originally bundled in this change has been removed — it is unrelated to the exception-escape bug and would have been a stealth behavior change for any non-primitive T routed through the fallback. Any future change to the null/empty contract for non-nullable value types should be a separate, intentionally scoped change.

Root Cause

ParserDelegateCache.Get<T>() only branches on the primitive types that have a dedicated TryParse-based parser (string, bool, int, long, short, float, double, decimal, DateTime/DateTimeOffset/DateOnly/TimeOnly and their nullable variants, Guid, enums, and arrays). Every other T — including all unsigned integer types, sbyte, char, and any custom TypeConverter-attributed type — falls through to MakeTypeConverterConverter<T>(), which calls typeConverter.ConvertFrom(...) without a try/catch. For invalid input (for example, "-42" parsed as uint, "4294967296" as uint, "AB" as char, or any input that a custom TypeConverter rejects), the exception propagates out of TryConvertTo<T>, breaking the Try* contract.

The same issue was previously fixed for Guid in #39649; this PR extends the same pattern to the generic fallback path so that any exception thrown by TypeConverter.ConvertFrom is converted to false.

Testing

Added comprehensive unit tests in BindConverterTest.cs to validate handling of unsigned integer types across all key scenarios. The tests ensure:

✅ Valid unsigned integer, sbyte, char, and custom TypeConverter conversions succeed as expected

✅ Negative inputs for unsigned types return false without throwing

✅ Out-of-range and overflow values return false (verifies OverflowException handling)

✅ Invalid strings return false consistently across all supported types

✅ Null and empty string inputs are handled gracefully for nullable types

✅ Nullable unsigned, sbyte, and char conversions behave correctly

✅ Boundary values (MinValue/MaxValue) are processed accurately for numeric types

✅ Character conversion accepts single-character values and rejects multi-character strings

✅ Custom TypeConverter JsonException scenarios return false as expected

✅ Custom TypeConverter exceptions other than JsonException are caught and return false (verifies converter exception handling)

Before Fix:

image

After Fix:

image

Fixes #42435

@irfanajaffer
irfanajaffer requested a review from a team as a code owner June 9, 2026 09:46
@ilonatommy

Copy link
Copy Markdown
Member

Let me add a bit more context.

The docs confirm the Try-prefixed contract of not throwing. The issue got half-fixed for Guid in #39649. Current state is that we have 2 groups, one well behaved and one throwing:

  • return false: types that have a dedicated Try*-based parser in ParserDelegateCache.
    string, bool, int, long, short, float, double, decimal, DateTime, DateTimeOffset, DateOnly, TimeOnly, Guid, their nullable forms, enums, and arrays. These use TryParse, so invalid input just returns false.
  • throw ArgumentException: everything that falls through to the TypeConverter fallback (MakeTypeConverterConverter -> ConvertWithTypeConverter), because it calls typeConverter.ConvertFrom with no try/catch. uint, ulong, ushort, byte, sbyte (+ nullable), char, and any BCL/custom type resolved via a TypeConverter.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes BindConverter.TryConvertTo<T> when conversion relies on TypeConverter, ensuring parse failures for unsigned numeric types (and similar converters) return false instead of throwing (notably covering ArgumentException from unsigned conversions). It also expands unit test coverage to validate the corrected behavior across several unsigned/edge-case scenarios.

Changes:

  • Update the type-converter-based conversion path to catch ArgumentException (and JsonException) and return false on parse failure.
  • Adjust null-input handling for type-converter conversions so non-nullable value types return false.
  • Add extensive unit tests for unsigned types (uint, ushort, ulong, byte) and sbyte, including nullable variants and boundary/invalid inputs.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.

File Description
src/Components/Components/src/BindConverter.cs Extends the TypeConverter fallback to treat more conversion failures as non-throwing false results and tightens null handling.
src/Components/Components/test/BindConverterTest.cs Adds new test coverage for unsigned numeric conversions (and sbyte) including invalid/negative/overflow/null/empty/boundary cases.

@ilonatommy ilonatommy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

First, shallow pass.

@irfanajaffer irfanajaffer changed the title Fix exception on parse failure for unsigned types in BindConverter Fix TryConvertTo<T> throwing exceptions in the TypeConverter fallback path Jul 9, 2026
@irfanajaffer
irfanajaffer marked this pull request as draft July 9, 2026 09:53
@irfanajaffer
irfanajaffer marked this pull request as ready for review July 9, 2026 11:43
@PureWeen

Copy link
Copy Markdown
Member

/review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Assert.Null(actual);
}

private static bool TryConvertUnsigned(string typeKey, string incomingValue, bool isNullable, out object actual)

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Source-only review of frozen head 31b7ae245a11b501c86bbe23bcb709fccccc7d20 found one unresolved P2 candidate: the repository proves that unsigned input reaches the new TypeConverter exception filter and that an unmatched exception would violate the TryConvertTo contract, but the frozen evidence does not include the target BCL converter implementation needed to establish its exact exception type.

Both routed guides completed with gpt-5.6-sol: CrossCuttingGuidance found no concrete candidate; BlazorComponentsGuidance raised the external-runtime candidate published inline after independent verification downgraded it as unresolved. Existing feedback contained no equivalent current finding requiring deduplication; older null-handling feedback was addressed in the frozen head.

Provenance: manifest v2 bundle; merge base c7fc0077f01b1069028af41b1dd90ddc090af63f; base tip and immutable guidance commit 7c704fed602c54d174e5674aee7b2eefe57073c9. Tests, target code, CI, browser workflows, and samples were not executed under the hosted source-only boundary. Runtime behavior of the external BCL converter remains uncovered; security assessment was explicitly excluded. Tracked Git bytes only; symlink, submodule, and LFS targets cannot establish behavior.

Generated by ASP.NET Core Pull Request Review for #67091 · copilot · gpt56 · 228.4 AIC · ⌖ 8.39 AIC · ⊞ 20.1K
Comment /review to run again


value = (T)converted;
return true;
catch (Exception ex) when (ex is NotSupportedException || ex is FormatException || ex is OverflowException || ex is ArgumentException || ex is JsonException)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2][UNRESOLVED] Invalid unsigned input may still escape this filter

TryConvertTo<uint>("-1", CultureInfo.InvariantCulture, out _) reaches this TypeConverter fallback. If the target BCL numeric converter wraps the parse failure in a plain Exception, it is not matched here, so TryConvertTo throws instead of returning false and form consumers cannot report their normal validation error.

Why unresolved: The frozen repository establishes the routing, filter, API contract, and conditional consumer effect, but it does not include target-version BCL source or immutable execution evidence proving the converter selected for uint and its exact exception type.

Minimal repro: BindConverter.TryConvertTo<uint>("-1", CultureInfo.InvariantCulture, out _).

Suggested fix if confirmed: add the converter's exact wrapper exception to the filter, or route these numeric types through dedicated TryParse-based parsers rather than catching arbitrary exceptions.

@PureWeen

Copy link
Copy Markdown
Member

Copilot's local review panel found no issues to raise at this commit.

The three independent local arms reviewed 31b7ae245a11b501c86bbe23bcb709fccccc7d20 and found no new, non-duplicate findings. Existing current-head review comments are not repeated or resolved here.

Informational discarded checks (non-blocking):

  • BindConverter.cs:2121-2160: broader exception suppression, converter-discovery failures, and application-setter failures. The new catch is limited to the selected conversion exceptions; setup and setters remain outside it.
  • BindConverter.cs:2091-2142 and EventCallbackFactoryBinderExtensions.cs:1350-1436: changed null defaults, partial-array exposure, or overwriting bound fields after invalid input. The reviewed old/new paths preserve those existing decisions.
  • BindConverterTest.cs:893-899: a false-pass or wrong-test-layer concern for the explicit throwing-converter regression. It reaches the actual managed conversion owner; its old/new behavior was also exercised by one arm.
  • BindConverterTest.cs:480,979: formatting and test-style nits were discarded as non-behavioral.

Posted for informational purposes so the author can confirm the verifier didn't discard or leave unresolved a real finding; this item does not block agent-reviewed-approved. These are routine negative checks; no arm had a surviving new candidate requiring the post-gate verifier.

Untested coverage gaps: Other runtime versions, browser workflows, publishing/trimming, and performance were not exercised. These limits are not blocking findings.

Validation boundary: G and S performed source review. O ran scoped managed BindConverterTest validation on the repository's .NET 12 alpha runtime: 129 passed at head; reverting only the product fix produced 40 failures. Its isolated build used generated build files, AllowMissingPrunePackageData=true, and placeholder JS assets unused by these managed tests; this is not browser or CI validation.

Human-directed and GitHub Copilot-generated.

@kotlarmilos
kotlarmilos self-requested a review November 24, 2026 16:13
@kotlarmilos
kotlarmilos merged commit cbf730f into dotnet:main Nov 24, 2026
31 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 10%

No docs needed: confident bug fix in BindConverter.cs with tests; signals showed no_signal.

Documentation surfaces considered

  • Conceptual article: Not required — Bug fix restoring the Try* contract; no new or changed public API surface or documented behavior.
  • Migration guidance: Not required — No upgrade action is needed; failures now return false instead of throwing.
  • Breaking change: Not required — No concrete compatibility break; the previously escaping exceptions now return false per the Try* contract.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 909e2764 Deployed Nov 24, 2026 by kotlarmilos via conclusion #451
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-reviewed-approved area-blazor Includes: Blazor, Razor Components pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BindConverter throws exception on parse failure

5 participants