3

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?

chriptus13
  • 705
  • 7
  • 20

1 Answers1

1

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}));
Paul
  • 139,544
  • 27
  • 275
  • 264
  • 2
    Ya I knew about that but I'm not sure which one is better. – chriptus13 Dec 06 '18 at 21:39
  • 1
    @chriptus13 They're the same. A thrown exception inside a Promise callback just gets converted into a rejected Promise using exactly this method. I like the syntax of `throw` slightly better, but not as a one liner. – Paul Dec 07 '18 at 15:58