Implement proper C# exception handling for HybridWebView JS→C# invocations #31484
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
This PR implements proper exception handling for HybridWebView when JavaScript calls C# methods. Previously, C# exceptions were silently caught, logged, and
nullwas returned to JavaScript, making it impossible for JavaScript callers to detect or handle errors properly.Problem
The original issue reported that HybridWebView was hiding exceptions thrown by C# methods during JS→C# invocation:
Solution
The fix implements a comprehensive exception handling mechanism that:
Key Changes
C# Side (
HybridWebViewHandler.cs)Added
DotNetInvokeErrorclass to represent .NET exceptions:Extended
DotNetInvokeResultto include optional error information:Modified
InvokeDotNetAsync()to return error information instead of null when exceptions occurAdded
CreateInvokeError()helper method and updated JSON serialization contextJavaScript Side (
HybridWebView.js/.ts)invokeDotNet()function to check for error responses:Usage After Fix
JavaScript can now properly catch and handle C# exceptions:
Testing
Added comprehensive tests covering:
Benefits
✅ Addresses core issue requirement - JavaScript can now catch C# exceptions in try-catch blocks
✅ Exception details preserved - type, message, and stack trace are accessible to JavaScript
✅ Proper logging maintained - both browser console and .NET logger continue to work for debugging
✅ Backward compatibility - successful method calls work exactly as before
✅ Developer-friendly - clear error messages and comprehensive debugging information
Fixes #27096.
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.