NotFound exception filter

An exception filter for entities that are not found.

Let's begin with the simpler case: when an entity is not found. To start, let's go back to the UsersService and look at the findOne() method. We may then replace the repository's findOne() call with findOneOrFail(). Now, instead of returning null, an error will be thrown by TypeORM, the EntityNotFoundError. When searching for a user that does not exist, we can then notice that an Internal Server Error exception is thrown.

Obviously, this exception is too generic. But we can catch the error to return something more appropriate, so we are well on our way. We want to automatically throw a NotFoundException whenever this error occurs. And to achieve this, we'll use an exception filter.

Last updated