1

Okay, I'm open to being told I'm approaching the problem incorrectly, so go ahead if that's the case, but I have a unhandled exception provider I'm adding to my builder.Services in program.cs, along with some data services. I can't figure out a good way to add an existing data service to the unhandled exception provider (custom logging to a db via the data service).

I had tried passing it, or using it via injection, but in the exception provider the data service keeps coming up as null in practice.

So I was thinking, is there a way to get a reference to the WebApplication that is running (the one we are running via app.Run() in Program.cs) from elsewhere in the running program.

Logically, I'd like to do something like this in the unhandled exception provider:

MyService = GetRunningApp().services.BuildServiceProvider().GetService<IMyService>();

Am I missing an easier way to do this?

Mike
  • 43
  • 5

1 Answers1

2

In Blazor it's not as easy to inject the middleware for global error handling like it is with Web API (Correct me if I'm wrong!)

For Blazor I think the closest we have is the <ErrorBoundary>. Check out this solution by Alamakanambra. They provide an example on how to create a component that handles global exceptions. You can do whatever logging or handling you need in the OnErrorAsync.

protected override Task OnErrorAsync(Exception exception)
{
    receivedExceptions.Add(exception);
    return base.OnErrorAsync(exception);
}
clamchoda
  • 4,411
  • 2
  • 36
  • 74
  • But how do I use this in say a .cshtml page? I'm using a login call done in on a cshtml page so I can access cookies for authorization. I'd like all my error handling to be as similar as possible, but it seems I need to do three different approaches (one for blazor components, one for cshtml, one for unhandled), and the global unhandled doesn't seem to work for me. It'll need access to this data service. – Mike Jul 15 '22 at 11:48
  • 1
    @Mike Unfortunately `ErrorBoundary` is for catching errors in components. What I could recommend is injecting a logger into `OnErrorAsync` *and* your other error handling on the .cshtml pages. At least all errors will report to the same place. – clamchoda Jul 15 '22 at 18:11