Reputation: 2259
I have an array of errors on my backend which I want to send back to client to display.
I'm making the request in my action like so
export const registerUser = registeredUserData => async (dispatch) => {
const response = await axios.post('/user/register', registeredUserData);
};
And on backend I have something like this
if (errors && errors.length) {
res.status(400).json({ errors });
}
My question is how can I get errors array back to the client?
I tried wrapping await
in try catch
but error
in catch
only contains a name of error
and it doesn't have the data
.
What works is if I get rid of status(400)
. Then it is gets handled like succesfull call and data is assigned to response
variable.
Is there a way to keep status of error and at the same time catch the data on client side?
Upvotes: 1
Views: 1602
Reputation: 20755
You can use this,
export const registerUser = registeredUserData => async (dispatch) => {
axios.post('/user/register', registeredUserData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
Upvotes: 1
Reputation: 1257
Use try/catch in your function
try {
const response = await axios.post('/user/register', registeredUserData);
} catch (e) {
console.log(e);
}
When success request comes then you will get data in the response
or catch
block will print the error.
Upvotes: 2
Reputation: 1499
Do this:
catch (error) {
if (error.response) {
console.log(error.response.data); // => the response payload
}
}
Upvotes: 7