mgh
mgh

Reputation: 407

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)

Upvotes: 2

Views: 18243

Answers (3)

pedro lucas
pedro lucas

Reputation: 21

If this error response don't show "here!!" In console, certainly the error is caused before this code section, probably in axios declaration or axios request form.

Try configure axios options inside a json object like:

axios({ method: "post", url: "..."

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202618

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

Upvotes: 1

Travis James
Travis James

Reputation: 1939

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

Upvotes: 7

Related Questions