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

1
  • 1
    Make upperFn return the promise, and then handle the promise rejection. You cannot handle asynchronous errors with a synchronous try/catch. Commented Nov 5, 2021 at 4:22

3 Answers 3

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)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Isn't part of the point of promises to avoid try..catch (which id decidedly ugly), hence Promise.prototype.catch?
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

6 Comments

This is not working for me, it's sending me this err: Uncaught (in promise), but in my case the FetchSomeThing function is a firebase function that I can change
` err: Uncaught (in promise)` means there is an error but you don't catch it, can you please show me your code? Also the code in your question is not correct, it should be like this: ` FetchSomeThing() .catch(err => { console.log(err) })`
This way is working thanks for the time!
|
-1

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

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

1 Comment

I was not missing the err in my real code, but I have found a way to solve my problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.