why the exception is not taken into account in the promise’s catch clause?

processURL() is not an async function. Thus, it does not automatically return a promise and does not automatically catch exceptions and turn them into a rejected promise.

So, if an exception is thrown anywhere in processURL(), that exception just propagates upwards as a synchronous exception. If you want to catch that synchronous exception yourself, you will need a try/catch in order to catch it.

Or, you could make processURL() an async function and then it will automatically catch any synchronous exceptions and turned them into a rejected promise that you could then catch with .catch() like this:

private async processUrl(url: string): Promise {
  const targetHostname = new URL(url).hostname; // exception thrown here invalid url something
  // do something else ...
  return Promise.resolve(targetHostname);
}

Or you could catch it manually:

private processUrl(url: string): Promise {
  try {
      const targetHostname = new URL(url).hostname; // exception thrown here invalid url something
      // do something else ...
      return Promise.resolve(targetHostname);
  } catch(e) {
      return Promise.reject(e);
  }
}

You may also have an issue here:

const {result} = this.processUrl(url).catch(error => error);

Because your processUrl() function is set up to return a promise. You need to use .then() or await to get the value out of that promise. FYI, if processUrl() is actually entirely synchronous, then it is just complicating matters to make it return a promise when it could just return a value directly.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top