Error handling in function returning another function's Promise

时间:2018-03-25 20:02:06

标签: typescript error-handling es6-promise

I'm pretty new to ES6 Promises and was wondering about error handling in the following situation:

// Base function
private async someFunction(...): Promise<T> {
    // returns Promise<T>
}

public async anotherFunction(...): Promise<T> {
    try {
        // stuff
        return someFunction(...);
    } catch (error) {
        return Promise.reject(error);
    }
}

anotherFunction returns someFunction with various parameters. My question is, is a try/catch here enough to handle errors thrown by someFunction? or should I be doing return someFunction(...).catch(err => ...) or is this just bad practice entirely?

Thanks

1 个答案:

答案 0 :(得分:1)

This will not work.

try{
  Promise.resolve(1)
    .then(() => {
      throw new Error('111');
    });
} catch (e) {
  console.log(e);
}

And this will not work.

try{
  Promise.resolve(1)
    .then(() => {
      return Promise.reject('something is wrong');
    });
} catch (e) {
  console.log(e);
}

But this is working.

Promise.resolve(1)
  .then(() => {
    try{
      throw new Error('Something is wrong...');
    } catch (e) {
      return Promise.reject(e.message);
    }
  })
  .catch((reason) => {
    console.log(reason);
  });