Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

javascript - How to pass error in a catch once a promise has resolved?

I have an api call. In case it fails, I want to get an error. Why does the error appears in the then() and not in the catch()? How to access it from catch? I'd prefer not having to write a long function inside of the then() such as if !res &&, etc.

Here is the code:

const postStuff = async () => {
  try {
    const res = await ax.post("/stuff");
    return res;
  } catch (err) {
    return new Error();
  }
};

export default function App() {
 React.useEffect(()=> {
    postStuff()
    .then(res=> console.log("res", res))
    .catch(err=> console.log("err", err))
 }, [])
  return (
    <div className="App">
     hello world
    </div>
  );
}
question from:https://stackoverflow.com/questions/65540608/how-to-pass-error-in-a-catch-once-a-promise-has-resolved

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you're just returning the error after catching it, it'll no longer reach the catch block inside useEffect.

Just throw the error in the catch block:

const postStuff = async() => {
  try {
    const res = 'bla';
    throw new Error();
    return res;
  } catch (err) {
    throw new Error();
  }
};

postStuff().then(res => console.log('then', res))
  .catch(err => console.log('catch', err))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...