2

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

ryan g
  • 308
  • 2
  • 12
  • Is SubstringValue() your code? – H H Mar 18 '21 at 17:06
  • Nope I don't have that in. I know where the Null Reference exception is in this case. I'm looking for a way to have a line number in the output of where the exception occurred. If I'm not mistaken this plumbing has to be done by the mono guys? – ryan g Mar 18 '21 at 17:33

1 Answers1

0

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}");
        }
    }
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Cory Podojil
  • 776
  • 2
  • 10
  • No offense taken. Actually I welcome criticism. The reason I ask is because the Microsoft team actually spoke about addressing this seeing that every other programming model they've put forth supports this, except blazor. – ryan g Mar 20 '21 at 17:52
  • Just as an added note. I do use try catches with pretty much all I write but you still can't extract a line number out of the Exception object. – ryan g Mar 20 '21 at 17:59