Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-catch is not working for 400 errors in JS

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)
like image 307
mgh Avatar asked Nov 28 '25 20:11

mgh


2 Answers

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);
    }
  }}
  />
like image 149
Travis James Avatar answered Dec 01 '25 10:12

Travis James


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.

Edit strange-pine-ozzq1

like image 28
Drew Reese Avatar answered Dec 01 '25 10:12

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!