DoneDeal0
DoneDeal0

Reputation: 6257

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>
  );
}

Upvotes: 2

Views: 666

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

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))

Or remove the try catch in postStuff:

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

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

Upvotes: 3

ANKIT MISHRA
ANKIT MISHRA

Reputation: 42

Instead of returning from inside postStuff catch block you need to throw error


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

Upvotes: 1

Related Questions