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!.
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffeeCode
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!