This is getting on my nerves, I've been checking the code for a few hours and can't spot the problem. in the below code, I'm using an invalid object in the body in order to get 400 error (Bad Request) and therefore catch it in the catch block:
<button onClick={() => {
try {
axiosInstance.post('/cart', { field: "invalid field" });
} catch (err) {
console.log("here!!!");
console.error(err);
}
}}
/>
I can see the request fail in network tab, in console I can see:
POST http://api.[REDACTED]/api/cart 400 (Bad Request)
index.js:1375 Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
Axios http requests are async, you need to use Promises or async/await. Try this and you will see the error response:
<button onClick={async () => {
try {
const response = await axiosInstance.post('/cart', { field: "invalid field" });
} catch (err) {
console.log("here!!!");
console.error(err);
console.error(err.response);
}
}}
/>
Https requests are asynchronous, you need to make the handler async and await the result of the call.
<button
onClick={async () => {
try {
return await axiosInstance.post('/cart', { field: "invalid field" });;
} catch (err) {
console.log(err);
}
}}
>
async press me
</button>
The following sandbox shows each side-by-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With