Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Sep 4, 2025

Overview

This PR implements proper exception handling for HybridWebView when JavaScript calls C# methods. Previously, C# exceptions were silently caught, logged, and null was 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:

// Before: C# exceptions were hidden, JavaScript got null result
try {
    const result = await window.HybridWebView.InvokeDotNet('MethodThatThrows');
    // This would execute even if C# method threw an exception
    console.log('Result:', result); // result would be null
} catch (error) {
    // This catch block was never reached for C# exceptions
    console.log('Never reached');
}

Solution

The fix implements a comprehensive exception handling mechanism that:

  1. Captures C# exceptions and serializes them with type, message, and stack trace information
  2. Returns error responses to JavaScript instead of null when exceptions occur
  3. Throws proper JavaScript errors that can be caught in try-catch blocks
  4. Preserves logging functionality for debugging purposes

Key Changes

C# Side (HybridWebViewHandler.cs)

  • Added DotNetInvokeError class to represent .NET exceptions:

    private sealed class DotNetInvokeError
    {
        public string? Type { get; set; }
        public string? Message { get; set; }
        public string? StackTrace { get; set; }
    }
  • Extended DotNetInvokeResult to include optional error information:

    private sealed class DotNetInvokeResult
    {
        public object? Result { get; set; }
        public bool IsJson { get; set; }
        public DotNetInvokeError? Error { get; set; }  // New field
    }
  • Modified InvokeDotNetAsync() to return error information instead of null when exceptions occur

  • Added CreateInvokeError() helper method and updated JSON serialization context

JavaScript Side (HybridWebView.js/.ts)

  • Enhanced invokeDotNet() function to check for error responses:
    // Check if the response contains an error
    if (response.Error) {
        const error = response.Error;
        console.error('Error invoking .NET method:', error);
        
        const jsError = new Error(error.Message || 'An error occurred while invoking a .NET method');
        if (error.Type) jsError.dotNetType = error.Type;
        if (error.StackTrace) jsError.dotNetStackTrace = error.StackTrace;
        
        throw jsError;
    }

Usage After Fix

JavaScript can now properly catch and handle C# exceptions:

try {
    const result = await window.HybridWebView.InvokeDotNet('MethodThatThrows', 'parameter');
    console.log('Success:', result);
} catch (error) {
    // This now properly catches C# exceptions!
    console.log('Exception type:', error.dotNetType);           // "InvalidOperationException"  
    console.log('Exception message:', error.message);           // C# exception message
    console.log('Stack trace available:', !!error.dotNetStackTrace); // true
}

Testing

Added comprehensive tests covering:

  • Various C# exception types (InvalidOperationException, ArgumentException, NotSupportedException, custom exceptions)
  • Both synchronous and asynchronous method exceptions
  • Stack trace preservation and error property accessibility
  • Backward compatibility for successful method calls

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.

Copilot AI changed the title [WIP] HybridWebView needs a consistent and usable story for handling C# methods that throw exceptions Implement proper C# exception handling for HybridWebView JS→C# invocations Sep 4, 2025
Copilot AI requested a review from mattleibow September 4, 2025 16:38
Copilot finished work on behalf of mattleibow September 4, 2025 16:38
Copilot AI and others added 3 commits September 9, 2025 03:32
Co-authored-by: mattleibow <1096616+mattleibow@users.noreply.github.com>
…tion handling

Co-authored-by: mattleibow <1096616+mattleibow@users.noreply.github.com>
@mattleibow
Copy link
Member

Closing in favour of #31521

@mattleibow mattleibow closed this Sep 9, 2025
@mattleibow mattleibow deleted the copilot/fix-27096-2 branch September 9, 2025 20:32
@github-actions github-actions bot locked and limited conversation to collaborators Oct 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HybridWebView needs a consistent and usable story for handling C# methods that throw exceptions

2 participants