in the nest.js app we can set @HttpCode()
for response HTTP status code for method! now I want to change HTTP status code in if condition in the method body of the controller
for example:
@Get()
@HttpCode(200)
findAll() {
if(condition){
// Question is: How Can i return response with 409 HTTP status code
}
return this.response.success(
[
{ id: 12, first_name: 'test1' },
{ id: 13, first_name: 'test 2' },
],
'success',
);
}
You can use the built-in HttpException class for this and NestJS will take care of formatting the response to the client
@Get()
@HttpCode(200)
findAll() {
...
if(condition){
// Question is: How Can i return response with 409 HTTP status code
throw new HttpException('Your message goes here', HttpStatus.CONFLICT);
}
...
}
https://docs.nestjs.com/exception-filters#throwing-standard-exceptions
V. Lovato gave a great answer. If you're looking for something a bit simpler you could just use the HttpException wrappers that nest provides:
if (condition) {
throw new ConflictException("You can add a message here or leave it empty")
}
If you'd like to know more about HttpExceptions that nest wraps, check them out here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With