Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 474
Rasoul Karimi Avatar asked Oct 19 '25 12:10

Rasoul Karimi


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

like image 68
V. Lovato Avatar answered Oct 21 '25 18:10

V. Lovato


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

like image 22
Ilia Avatar answered Oct 21 '25 17:10

Ilia