How can i send error codes in nestjs apart from 200? i tried to inject response object in a method but there is no method to send error.
save(@Body() body: any, @Res() response: Response): string {
console.log("posting...")
console.log(body)
return "saving " + JSON.stringify(body)
}
the above code send body with 20X status i want to send different status code like 400 or 500.
You should use exception filters in your case instead.
In your case you'll need:
throw new BadRequestException(error);
Or you can use
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
That will return
{
"statusCode": 403,
"message": "Forbidden"
}
Docs: https://docs.nestjs.com/exception-filters
So the complete example of returning http status code without neither throwing errors, nor via static @HttpCode()
:
import { Post, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
...
@Post()
save(@Res() response: Response) {
response
.status(HttpStatus.BAD_REQUEST)
.send("saving " + JSON.stringify(body));
}
You need to get use of the @Res()
decorator to get hold of the underlying express
Response
object and use it's status()
method.
Though I still wonder if there is some other way not involving operating stateful objects and just making a clean return in nestjs like you would do in spring...
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