Published on

Simplify Exception Handling with Exception Filters

Authors

Error handling in C# has traditionally been very verbose. You had to either catch everything and rethrow, or end up with nested if checks inside your catch block.
This is where exception filters comes to the rescue.

What did we do before?

Imagine you only want to catch a HttpRequestException if the status code is 404. Without filters, you’d probably do something like this:

try
{
    await FetchData();
}
catch (HttpRequestException ex)
{
    if (ex.StatusCode == HttpStatusCode.NotFound)
    {
        Console.WriteLine("Resource not found.");
    }
    else
    {
        throw;
    }
}

It works as intended, but it is a bit clunky. You have to rethrow manually, when condition is not met. Furtheremore the catch job has multiple responsibilities.

With exception filters

Let's have a go at it with exception filte

try
{
    await FetchData();
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
    Console.WriteLine("Resource not found.");
}

This is MUCH nicer, right? The condition is directly in the catch statement, and there is no need for rethrowing anything.

This will give us

  • Cleaner code - the logic is in the declaration instead.
  • No unnecessary rethrows - exceptions that do not match the filter, just bubble up automatically.
  • Intent - the intent is obvious.

When do I actually use this?

  • I reach for exception filters when I only care about certain error details, like a specific StatusCode or ErrorCode.
  • They’re a lifesaver if I want to handle something only when I’m debugging, for example, with when (Debugger.IsAttached).
  • And honestly, if my catch block is turning into a mess of if statements, a filter usually cleans it right up.

I didn’t use exception filters much at first, but now I find them really useful for keeping my error handling straightforward. If you’ve got an old “catch and rethrow” block lying around, try swapping in a filter and see how it feels. You might not want to go back.