rickygrimes
rickygrimes

Reputation: 2716

Javascript error handling with throw and catch block

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

Upvotes: 1

Views: 55

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20924

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

Upvotes: 3

Related Questions