1
votes

I was thinking there were no differences between:

@Post()
saveClient(@Param() params, @Body() createClientDto: ClientDto) {
   this.clientRepository.save(createClientDto);
  }

and

@Post()
  async saveClient(@Param() params, @Body() createClientDto: ClientDto) {
   await this.clientRepository.save(createClientDto);
  }

But without async/await the function returns void, and If an exception is occurred I get this:

(node:62777) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection. (node:62827) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

With async/await the above Warning is not displayed, since the function returns a Promise. The same if I add a return:

@Post()
saveClient(@Param() params, @Body() createClientDto: ClientDto) {
   return this.clientRepository.save(createClientDto);
  }

So I'm a bit worried: a simple missing return may terminate my nestjs process?

Thanks

1
Yes. Failure to return a promise in your first example means that nobody is paying attention when that operation has an error as there is no local .catch() so the only way for the caller to handle an error is for you to return it. That's a fundamental promise programming mistake to not either return the promise so the caller can handle errors or to handle errors locally with .catch().jfriend00
I'd recommend using with '@typescript-eslint/no-floating-promises': 'error'. NestJs handling (or NodeJS here) is correct - if you don't want to return this to the API client, you'll need an await. Otherwise use return (goes well with exception filters). In case you want to expect errors and still show "success" to the API client, use .catch() and handle it there.Can

1 Answers

0
votes

try to wrap it in try / catch

@Post()
  async saveClient(@Param() params, @Body() createClientDto: ClientDto) {
    try {
       await this.clientRepository.save(createClientDto);
    } catch(err) {
       console.log(err);
    }
  }