Should I make a mistake or return a rejected promise inside an asynchronous function?

I work with promises provided by the AWS JS SDK . The essence of what I do when I create an asynchronous function that wraps the AWS SDK looks like this:

module.exports.myCustomFunction = input => {

    if (badInput) {
        throw new Error('failed') // <-- This is they key line
    }

    return sns.createTopic(someParams).promise()
}

// The caller looks like this:
myModule.myCustomFunction(someInput).then(result => {
    // carry on
})
.catch(err => {
    // do something with the error
})

I was approached by someone who said that I should never throw an error inside these functions based on promises. Instead, they offered to return Promise.reject('failed'). Honestly, I'm not so good at promises, but their explanation seems to have crossed my mind.

+4
source share
3 answers

They are true.

myCustomFunction , (.then .catch promises, ). , .

, :

try {
  myModule.myCustomFunction(someInput).then(result => {
    // carry on
  })
  .catch(err => {
    // do something with the error
  })
} catch(err) {
  ...
}

, , : try/catch .catch promises, sns.createTopic(someParams) .

Promise.reject():

module.exports.myCustomFunction = input => {

    if (badInput) {
        return Promise.reject('failed');
    }

    return sns.createTopic(someParams).promise()
}

.catch /.

NB: Node.js(v7.6 , ), :

module.exports.myCustomFunction = async input => {

    if (badInput) {
        throw new Error('failed');
    }

    return sns.createTopic(someParams).promise()
}

async. , ( , @peteb).

+1

A throw Promise/Promise Promise/Promise Chain.

const myFunc = input => {
  return new Promise((resolve, reject) => {
    if (badInput) {
      throw new Error('failed')
    }

    return resolve(sns.createTopic(input).promise())
  })
}

return myFunc('some input')
  .then(result => { 
    // handle result
  })
  .catch(err => { console.log(err) }) // will log 'failed'

myCustomFunction Promise, throw, Promise sns.createTopic().promise(). Promise , Promise.reject(new Error('failed')) throw.

+2

,

, TypeError(), , .

Joyent | :

, . . , - [...]

. , . ( ).

, , , Error() TypeError().

?

, , SDK AWS. , , , , , , - , , , API, ?

, , . , , . - , API undefined, .

?

(, , , , badInput), , :

try {
  if (badInput) {
    throw new Error('failed')
  }

  ...
} catch (error) {
  // expected error, proceed as normal
  // ...except not really, you have a bug
}

:

process.on('uncaughtException', function (error) {
  // deal with programmer errors here and exit gracefully
})

if (badInput) {
  throw new Error('failed')
}

try {
  ...
} catch (error) {
  // deal with operational errors here and continue as normal
}

Node.js, , , :

Example func | Kind of func | Example error  | Kind of error | How to   | Caller uses
             |              |                |               | deliver  |
==========================================================================================
fs.stat      | asynchronous | file not found | operational   | callback | handle callback
             |              |                |               |          | error
-------------+--------------+----------------+---------------+----------+-----------------
fs.stat      | asynchronous | null for       | programmer    | throw    | none (crash)
             |              | filename       |               |          |

, , , , , -, .

TL; DR

A function that must return a Promiseunder operating conditions must throwsynchronously when an error is caused by an error, and must rejectasynchronously when an error occurs in a correctly written program.

This reflects the official Joyent recommendation :

The best way to repair programmer errors is to work immediately.

0
source

Source: https://habr.com/ru/post/1682963/


All Articles