After reading this article you'll be able to build custom middleware, use it to intercept all unhandled exceptions and save these into a text file. You'll also learn how to do dependency injection inside ASP.NET Core middleware component.
Middleware is a piece of software that handles requests and responses in the middle of application pipeline. An example of built-in ASP.NET Core middleware is authentication component and response caching component. In this article I’ll show you how to create global exception handler using custom middleware component.
This article will teach you how to create global exception handler which will save each uncaught exception into file. Later on, you can also use it to send exceptions to 3-rd party service like Raygun (but it is not included in this how-to) or to do anything else you want with that exception.
It’s really easy to create basic middleware. It needs a constructor with a RequestDelegate parameter and an Invoke method which returns Task and which has a HttpContext parameter. Therefore our class should look like this:
Now, all requests are handled by this class. The Invoke method you saw earlier can perform additional actions before or after invocation of next pipeline component. The _next(httpContext) call runs other components.
Whenever exception is raised we catch it, we also make sure that it is rethrown. Let’s save contents of the exception into a file. For now we’ll hardcode file path to c:/app_exceptions/:
Most likely you will want to save your file somewhere within your app folder e.g. ~/logs. For this we’ll need to inject IHostingEnvironemnt dependency which exposes WebRootPath property.
In order to inject any dependency into middleware component you only have to add it as a parameter to the Invoke method. Here’s how the final version of our global exception handler should look like: