Centralize your .NET exception handling with filters

Door Niek Kuijken In .NET

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:

1*afoiaL1M9ktRFo7uBYPyiA@4x

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.

1*KG_jzaRrEZ_MXxf_TrQMAA@4x

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:

1*iYYF_uUaGzZLB0WaV0o67w@4x

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:

5@4x

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.

6@4x

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.

7@4x
This is what the EmployeeRepository.cs will look like.

Which you can then add in your filter:

8@4x

This will allow you to transfer your code from this:

9@4x
Before implementing IExceptionFilter.

To this:

10@4x
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:

  • IAuthenticationFilter
  • IAuthorizationFilter
  • IActionFilterThese
  • IResourceFilter
  • IResultFilter

They all have a specific order in the request pipeline, read more about it on this documentation page: link.

TLDR;

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!

Meer informatie

Niek Kuijken@4x

Niek Kuijken

.NET Developer

Stuur Niek een e-mail

Reacties

Er zijn nog geen reacties op dit bericht.

Plaats een reactie

Dit veld is verplicht.

Vul een geldig e-mailadres in.

Dit veld is verplicht.