Tracking down unhandled exceptions in Blazor Webassembly

1.8k Views Asked by At

Any idea on how to get the line number of an unhanded exception in blazor webassembly?

There was a discussion long ago on some work that still needs to be done by the team to have it working. I think that died down if I'm not mistaken.

Consider the message below. It leaves one completely in the dark with no guidance on where to start looking.

Thanks in advance.

enter image description here

1

There are 1 best solutions below

2
Cory Podojil On

Not to be rude, but it is in the Blazor documentation to always handle exceptions yourself when interacting with components: https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-5.0&pivots=webassembly#global-exception-handling

Simply wrap your all your method bodies (even the lifecycle methods) with a try/catch block. Bonus points to inject the ILogger<MyComponent> for friendly logging. Example:

@inject ILogger<MyComponent> Logger

<h1>@UserName</h1>

@code {
    private string UserName { get; set; } = string.Empty;
    protected override async Task OnInitializedAsync()
    {
        try
        {
            NavigationManager.LocationChanged += OnLocationChanged;
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            UserName = $"Hi, {authState.User.Claims.FirstOrDefault(x => x.Type == "display_name")?.Value}!";
        }
        catch (Exception ex)
        {
            Logger.LogError($"Failed to initialize MyComponent. Error: {ex}");
        }
    }
}