Adding a global exception handler

When an unhandled exception is thrown from a controller action, ASP.NET Core responds to the caller with the status code 500 (Internal Server Error). For the client, this status code means that something bad happened on the server but doesn't offer any meaningful information that the user can provide to the API support team (such as the request/correlation identifier).

To overcome this, we need to add a global exception handler — a piece of code that can intercept the calls made to the request pipeline and catch exceptions that were thrown. There is more than one way to add a global exception handler, but I believe the easiest way is by adding an Exception Filter that will be added to the MVC pipeline.

Get Hands-On Full-Stack Web Development with ASP.NET Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.