Search code examples
typescripterror-handlinges6-promise

Error handling in function returning another function's 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


Solution

  • 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);
      });