Javascript error handling with throw and catch block

Viewed 39

I have the below async function that throws an error if I am not running in test mode in the else block. If it is test mode, it executes a bunch of log statements in the execute function, and then jumps to createMyTestSuite where bad things may happen which I catch in the catch block. My question is, do I need to throw again from catch? I know the first throw will jump execution to the catch block.

  public static async load(testMode:Mode): Promise<void> {
    try {
      if (testMode) {
        execute();
      } else {
        throw new Error('Can only run test mode in load');
      }
      await this.createMyTestSuite();
    } catch(error) {
      dLogger?.error('failed to load create my test suite ', {error});
      throw error;
    }
  }
1 Answers

You can return a rejected promise from the catch block.

public static async load(testMode:Mode): Promise<void> {
  try {
    if (testMode) {
      execute();
    } else {
      throw new Error('Can only run test mode in load');
    }
    await this.createMyTestSuite();
  } catch(error) {
    dLogger?.error('failed to load create my test suite ', {error});
    return Promise.reject(error);
  } 
}
Related