how to change response http status code on method body in nest.js

Viewed 3477

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',
    );
  }

2 Answers

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

Related