Response setup
With everything ready, the response can be set up and sent.
With the status
, error
and message
in hand, it's time to setup the response
. We can chain the following methods:
status()
- Sets thestatus
of theresponse
json()
- Defines the returnedbody
With this, we return an exception following the same pattern as Nest.
response.status(status).json({
statusCode: status,
message,
error,
});
We have finished our first exception filter! We can then activate it globally in the DatabaseModule
.
Commit - Creating the not found exception filter
After this, we can search our code and, wherever we find something like this:
const user = await this.usersRepository.findOneBy({ id });
if (!user) {
throw new NotFoundException('User not found');
}
return user;
We may replace it with the following:
return this.usersRepository.findOneByOrFail({ id });
Only do this when the exception thrown is a NotFoundException
.
Commit - Cleaning find one calls
Last updated