skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Filter exceptions with when

C# 6

Code card showing a catch when filter that handles an HTTP 404. Output: Oh no, not found!

A when filter decides whether a catch block handles the exception. If false, the exception keeps propagating. Everything else propagates with its stack trace intact. On .NET 8+, filter on ex.HttpRequestError. It is available since C# 6. The key line is when (ex.StatusCode == HttpStatusCode.NotFound) in filters.cs. Run it and the output reads Oh no, not found!.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
filters.cs
using System.Net;
try
{
using var response = new HttpResponseMessage(
HttpStatusCode.NotFound);
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
when (ex.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("Oh no, not found!");
}
Output
$ dotnet run filters.cs
Oh no, not found!