#Throwing a new HttpException doesn't return any response

8 messages · Page 1 of 1 (latest)

keen laurel
#

I'm still discovering Nestjs and I can't understand how to return standard HTTP error.

For instance, in my controller, I have this endpoint defined (simplified for better readability):

@Post('login')
  checkLogin(@Body() body, @Res() res: Response) {
    this.loginService.checkLogin(body.login, body.password)
    .then((response) => {
      return response;
    })
    .catch(error => {
      this.logger.log(`Access Denied: ${error}`)
      throw new HttpException('Access Denied', HttpStatus.FORBIDDEN);
    })
  }

which calls the following service (with a bit of pseudo-code to keep it readable):

async checkLogin(login, password) {
        if(login and password are correct) {
            return Promise.resolve(user);
        }
        else {
            const error_msg = 'Access Denied'
            this.logger.log(error_msg);
            return Promise.reject(new Error(error_msg));
        }
}

When I test this endpoint with Postman, I get a socket hang up error and no proper response. The Nestjs logs show the thrown exception and that's it.

What am I missing? What am I doing wrong?
Thanks for any help.

merry temple
#

You use @Res(), meaning Nest expects you to send the response yourself. If this is not the desired behavior, you should use @Res({ passthrough: true })

keen laurel
#

Ah ok. In my case when the login is correct, I need to add data to the response, that's why I use @Res.
Thanks a lot for blazing fast help! I could solve it like that:

@Post('login')
  checkLogin(@Body() body, @Res() res: Response) {
    this.loginService.checkLogin(body.login, body.password)
    .then((response) => {
      return res;
    })
    .catch(error => {
      this.logger.log(`Access Denied: ${error}`)
      //throw new HttpException('Access Denied', HttpStatus.FORBIDDEN);
      res.status(HttpStatus.FORBIDDEN).json()
    })
  }
merry temple
#

I need to add data to the response
You're aware you can return the data from the controller and Nest will end up sending that as the response body, right?

keen laurel
#

Yes, I'm aware. In this case I needed to add a specific header to the response. Would that be possible otherwise?

merry temple
#

If you just need to add a header you can use the { passthrough: true } which tells Nest you're only modifying the response, but not sending it

keen laurel
#

oh ok, I see. I will try that then. Thanks!
I'm not sure how to add the solved tag now.