Tip #002
Filter exceptions with when
About this tip
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!.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffee
Railway
Referral
Need somewhere to deploy?
My link gets you $20 in credits.
Claim $20 creditI may earn a commission if you become a customer.
Code
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.csOh no, not found!