Hello my dear developers!
How do you feel today?
I’ve seen many times web API’s controller’s methods with ActionResult as return types. On these methods there are lots of defensive code so an appropriate status response can be generated. A neat trick to avoid crowding your controller methods handling exceptions is to user filters.
Filters are part of asp.net core pipeline, a middleware to handle recurring situation.
Filters in ASP.NET Core | Microsoft Docs
I based my solution on the following article since is a simple explanation (in net core 2.1 though):
Using ExceptionFilter for exception handling in AspNet Core Web API – Janak’s blog
I basically throw a domain exception an handle at in my own ExceptionFilter:
DoTasksBeforeReady/ExceptionFilter.cs at main · ambsenyestudi/DoTasksBeforeReady (github.com)
You just need to add it at Startup.cs on ConfigureServices and you are done
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(config=> {
config.Filters.Add(typeof(ExceptionFilter));
});
...
}
Happy coding and remember…there is life beyond coding🙂