Search code examples
node.jslambdapromisearrow-functions

Throwing errors without curly brackets in lambdas/arrow-functions


Assuming I want to transform an error when using promises in NodeJs.

So for instance using request-promise module in code underneath I'm trying to modify the error for a simpler one when making a GET for a certain URI.

const options = {
  'uri': uri,
  'headers': { 'Accept-Charset': 'utf-8' }
}

rp.get(options)
  .catch(err => {
    throw {'statusCode': err.statusCode ? err.statusCode : 503}
  })

Is there anyway I can omit the curly brackets like we do when using return?


Solution

  • throw is a statement, so you cannot use it where an expression is required. The version of an arrow function with no curly braces expects an expression. You can return a rejected Promise instead of throwing:

    rp.get(options)
      .catch(err => Promise.reject({'statusCode': err.statusCode ? err.statusCode : 503}));