Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling error from async await syntax with axios

Here's my chunk of code:

  const getToken = async () => {     try {       const token = await axios.post(keys.sessionURL, {         email: keys.verificationEmail,         password: keys.verificationPassword,       });     } catch (err) {       throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead     }   }; 

So as you can see I'm connecting to external server in order to get a token. And that works. Now, I'd like to catch an error but this time not with 'throw new error' but I'd like to send it to the user, so I'd like to have something like this instead:

res.status(401).send('Unable to get a token'); 

But because I'm not inside the route handler I cannot use 'res'. How can I send it to the user then?

Thank you!

like image 431
Murakami Avatar asked Sep 26 '18 07:09

Murakami


People also ask

Can I use async await with Axios?

To use the async/await syntax, we need to wrap the axios. get() function call within an async function. We encase the method call with a try... catch block so that we can capture any errors, similar to the catch() method we used in the Promise version.

How do you handle errors in Axios?

axios. get('/user/12345') . catch(function (error) { if (error.

How do you use async await with Axios in React?

To use async and await with Axios in React, we can call axios in an async function. We call axios with the URL we want to make a GET request to. It returns a promise that resolves to an object with the data property set to the response data. So we use await to return the resolved value from the promise.


1 Answers

For axios version-0.19.0 below code worked after hours of struggling with async await.Not sure about other versions though!

catch(error){ console.log(error.response.data.error) } 

Hope that helps!

like image 53
Akshay Seth Avatar answered Sep 30 '22 21:09

Akshay Seth