0

I'm stuck with the following problem:

function upperFn(){
    FetchSomeThing() 
    .catch(err => { 
        console.log(err) 
    })
}

function lowerFn(){
    try {
        upperFn()
    }
    catch (err){
        //Here its not working anymore
        console.log(err) // Catch is never used
    }
}

So I've tried to return the error and even rethrow it but nothing work's. I would be very happy if someone can explain me how to catch this error in my lower function.

Thanks

Laurent K
  • 15
  • 7
  • 1
    Make `upperFn` return the promise, and then handle the promise rejection. You cannot handle asynchronous errors with a synchronous `try`/`catch`. – Bergi Nov 05 '21 at 04:22

3 Answers3

0

I just figure out how to handle this probleme, simply by returning the whole function.

function upperFn(){
    return FetchSomeThing()
}

function lowerFn(){
    try {
        upperFn()
    }
    catch (err){
        //Here its working well
        console.log(err)
    }
}
Laurent K
  • 15
  • 7
  • Isn't part of the point of promises to avoid *try..catch* (which id decidedly ugly), hence [*Promise.prototype.catch*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch)? – RobG Nov 05 '21 at 03:46
0

Simply throw the error in upperFunction and try-catch it in the lowerFunction

function FetchSomeThing() {
  return Promise.reject("Something goes wrong.");
}

function upperFn(){
  FetchSomeThing().catch(error => {
    throw error;
  })
}

function lowerFn(){
  try {
      upperFn()
  }
  catch (error) {
      //Here its not working anymore
      console.log(error) // Catch is never used
  }
}

lowerFn()

Working example: https://codesandbox.io/s/agitated-thunder-3s9qj

Output:

enter image description here

Nawaf Khalifah
  • 594
  • 3
  • 11
-1

Maybe it's because you missed the error param after catch?

try {
  doSomeThing();
} catch (error) {
  console.error(error);
}