How To Extend Apple Watch Battery Life In watchOS 9

In addition to Apple releasing iOS 16 to the public a few weeks ago, we’ve also seen the release of watchOS 9 for the Apple Watch. Of course, there is currently more talk about the new iOS, which…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Automatically handle exceptions in .NET Core API

If you develop APIs in .NET Core, I’m sure this is quite familiar to you:

Is there anything particularly wrong with this code? Not really, just a normal Action which fetches a book and returns it if it has been found.

However, you see the if-statement which checks if the book was found in order to return the appropriate status code? Wouldn’t it be great to take that out of the controller? It is cluttering up the Action and causes us to repeat ourselves constantly, especially in a larger application. If we want to log this as well, even more space will be taken.

We can’t, however, move this code to another layer such as Business unless the business layer actually returns an IActionResult, which is ridiculous. What if we could simply throw an Exception in one of our application’s layers and have MVC handle this for us instead?

So how do we extract this from our controller and at the same time doesn’t require us to repeat ourselves? The answer is Action Filters. More specifically, a custom implementation of ExceptionFilterAttribute found in Microsoft.AspNetCore.Mvc.Filters.

Filters are a way to run code before or after certain stages of the request pipeline. An example of this is the [Authorize] attribute which checks if a user is authorized.

As mentioned above, in order to run code every time an Exception is thrown, we’ll have to create a custom ExceptionFilterAttribute.

Let’s quickly set up a basic example.
We have a single API project called ActionFilters.Api

There is an entity Book:

And a BookService inheriting from IBookService :

Add a comment

Related posts:

Misplaced egomania

I always thought that there was something peculiar about me. Something that made me different and set me apart from other people — and that made me standoffish. A lot, and in a rude way. I always…

How to define your KPIs in 3 steps

The definition of KPI (Key Performance Indicator) is: a metric chosen by you (Performance) that is relevant (Key) for your success (Indicator). That means you shouldn’t just copy a KPI from someone…

What are Public and Private Blockchains?

Since the beginning of blockchain technology, people have talked about public vs private blockchain. In an business environment, it’s actually really important to know the big differences between…