If your application is riddled with try-catch blocks, you might want to get familiair with Exception Filters. These are a type of middleware that you can hook into your request pipeline quite easily, which can give you a much more central and intuitive way of handling your errors.
Over the years I’ve seen many methods with error-handling similar to this:
The action is simple. We want to update the details of an Employee. Due to various rules, it might have a few different outcomes. Now we can handle these inside the method itself. But chances are, these will turn out to be very similar in other (API) methods.
Using Exception filters to catch them all
.NET offers the possibility to catch all (unhandled) exceptions in your request pipeline. First we need to add a class which implements the IExceptionFilter.
After this is done, it can be hooked into our request pipeline. You can wire it up in the ConfigureServices method of your Startup class:
That’s it! Your exceptions will now end up in our custom filter.
This opens up the possibility of moving your try – catches into the filter like so:
Which means you no longer have to catch it in your controller method. Or, any other place in your application for that matter, as long as it’s thrown during a call to your API.
Throw (custom) exceptions by default
Make exception throwing the de facto standard of handling errors. Explicitly throwing exceptions whenever something went wrong will simplify your code and make it even easier to handle your errors.
This is what the EmployeeRepository.cs will look like.
Which you can then add in your filter:
This will allow you to transfer your code from this:
Before implementing IExceptionFilter.
After implementing IExceptionFilter.
Take a look at the other filters as well!
Besides the IExceptionFilter, .NET offers a series of filters for different purposes that you can hook into your request pipeline just as easy:
They all have a specific order in the request pipeline, read more about it on this documentation page: link.
Simplify your error handling:
- Add a class which implements IExceptionFilter
- Put all your exception handling in this class
- Configure it in your ConfigureServices method in your Startup.cs
- Make your codebase more readable by removing all the try-catches
- Throw (meaningful) exceptions whenever something goes wrong
- Enjoy your clean codebase!