skip to Main Content

I’m converting some code from .then/.catch to async/await. I need to access the original promise that fails in the catch block for logging purposes.

Orignal code:

  const myPromise = somePromise()

  myPromsise.then(() => {
    //...
  }).catch((error) => {
    errorLogger(error, myPromise) // The way we log things requires the original promise to be passed to the error logger.
  }

With try catch

  try {
    const myPromise = await somePromise()
    //...
  } catch (error) {
    errorLogger(error, myPromise) // myPromise is not available in catch block due to scope.
  }

How can I access the promise in the catch block?

2

Answers


  1. You’re not setting myPromise() to the promise. By using await you’re setting it to what the promise resolves to.

    To get the promise itself, assign the function to a variable without using await. You can then use await separately to get the resolved value.

    const myPromise = somePromise();
    try {
        const myValue = await myPromise;
        //...
    } catch (error) {
        errorLogger(error, myPromise);
    }
    
    Login or Signup to reply.
  2. The way we log things requires the original promise to be passed to the error logger.

    Why? This doesn’t make sense, there are many ways code can fail without a promise being available. Really all the information that the logger needs should be contained in the error object that is thrown as the exception. Fix your logging.

    But if you must, I would start with

    try {
      const myPromise = somePromise();
      await myPromise.catch(err => { err.promise = myPromise; throw err; });
      …
    } catch (error) {
      errorLogger(error, error.promise)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search