Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send error codes in nestjs app from controller?

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.

like image 988
arshid dar Avatar asked Jan 01 '23 20:01

arshid dar


2 Answers

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

like image 61
Amadeusz Blanik Avatar answered Jan 08 '23 01:01

Amadeusz Blanik


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...

like image 21
Klesun Avatar answered Jan 08 '23 00:01

Klesun