Skip to content
Advertisement

Decorator to return a 404 in a Nest controller

I’m working on a backend using NestJS, (which is amazing btw). I have a ‘standard get a single instance of an entity situation’ similar to this example below.

JavaScript

This is incredibly simple and works – however, if the user does not exist, the service returns undefined and the controller returns a 200 status code and an empty response.

In order to make the controller return a 404, I came up with the following:

JavaScript

This works, but is a lot more code-y (yes it can be refactored).

This could really use a decorator to handle this situation:

JavaScript

Anyone aware of a decorator that does this, or a better solution than the one above?

Advertisement

Answer

The shortest way to do this would be

JavaScript

There is no point in decorator here because it would have the same code.

Note: BadRequestException is imported from @nestjs/common;

Edit

After some time with, I came with another solution, which is a decorator in the DTO:

JavaScript

Then in your DTO:

JavaScript

Hope it helps someone.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement