2

I'm using axios in my react app to send a POST to another server. If the server responds with an error 500 code, it shows in the chrome dev-tools:

POST http://192.168.1.2:3001/login 500 (Internal Server Error)

I'm handling the 500 code internally, and this is something that might happen in my app and is not considered an error.

Is it possible to configure axios not to log the error on the dev tools? I do not want the end user to see it.

Poogy
  • 2,597
  • 7
  • 20
  • 35
  • Possible Duplicate of https://stackoverflow.com/questions/44806333/unable-to-catch-and-log-the-error-response-from-an-axios-request/44806462#44806462 – Shubham Khatri Apr 14 '18 at 09:46

4 Answers4

7

Just an improvement of the above... To ensure that the error comes from your API call you can specify that on axios catch.

axios.post(
    /* ... */
).then(
    response => {/* do something with the response */}
).catch(
    error => if(error.response){
    console.log(error.response.data)
    // from here you get only the response that is generated from your API 
    and hence you can differrentiate if the error is local or external
}
);
Waweru Mwaura
  • 247
  • 1
  • 7
4

That is what the .catch() handler is there for. It gets called when the promise returned by axios.post()gets rejected:

axios.post(
    /* ... */
).then(
    response => {/* do something with the response */}
).catch(
    error => {/* do something with the error */}
);

But you should really handle that case on the server side. A server should never return a 500 response on purpose. This response indicates an unhandled error. If your server handles that error it should return a more appropriate error code. 500 messages should be considered a bug and should be fixed instead of trying to hide them from the user.

trixn
  • 15,761
  • 2
  • 38
  • 55
0

Here is the Sample to handle this case:

axios.post('/formulas/create', {
    name: "",
    parts: ""
})
.then(response => { 
})
.catch(error => {
});
0

What worked for me was the following code:

axios.post(`${BASE_URL}/`, data, config)
   .then(response => {
        if (response.data.success) {
            console.log(response.data.message);
            resolve(response.data.message)
        } else {

            reject(response.data.message)
        }
    }).catch(err => {

        let e = { ...err
    }

    console.log(e.response.data);
    reject(e.response.data)

   })

})

Everistus Olumese
  • 384
  • 1
  • 4
  • 16