Handle errors in ASP.NET Core web APIs

Handle errors in ASP.NET Core web APIs

Exception handling is one of the critical areas in modern web application development. If exceptions are not handled properly, the whole app can be terminated, causing severe issues for users and developers. Try-catch blocks are widely used in apps to handle exceptions. They are the most basic way of handling exceptions.


The above example is a typical case where we use try-catch block to handle the exception. The try-catch block method is ideal for novice developers, and it is something that every developer should be aware of. However, this technique has a disadvantage when working with massive projects with complex architectures. In such cases we have to use Exception Handling Middleware to handle the exceptions.

Exception handler

In Program.cs, call UseExceptionHandler to add the Exception Handling Middleware:

Configure a controller action to respond to the /error route:

Add [ApiExplorerSettings] attribute and set its IgnoreApi property to true to exclude the error handler action from the app's OpenAPI(Swagger) specification. Also Allow anonymous access to this controller to allow unauthenticated user to see the error.

Use exceptions to modify the response

In case you want to modify the contents of the response from outside of the controller using a custom exception and an action filter you will have to do the following.

Create an exception type named HttpResponseException:

Create an action filter named HttpResponseExceptionFilter: The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

In Program.cs, add the action filter to the filters collection:

Comments

Popular posts from this blog

SSL Certificate authentication in ASP.NET Core

Belekeri, Karwar Beach Photos

Publish an Angular with .NET CORE app to IIS on AWS Cloud EC2 instance