This may seem stupid, but I'm trying to get the error data when a request fails in Axios.
axios .get('foo.com') .then((response) => {}) .catch((error) => { console.log(error); //Logs a string: Error: Request failed with status code 404 });
Instead of the string, is it possible to get an object with perhaps the status code and content? For example:
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
By default, axios throws an error when it encounters any 4XX / 5XX status code. Adding this line overrides that default behavior. You can then check the status code yourself (in response. status ), conditionally handling the 404 as you need.
By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step.
It's not possible to retrieve response bodies for non 200 HTTP responses because Axios throws an exception for non 2xx codes. This does not complies to the browser Fetch API. Some APIs return data even if the response code is not 200 OK.
What you see is the string returned by the toString
method of the error
object. (error
is not a string.)
If a response has been received from the server, the error
object will contain the response
property:
axios.get('/foo') .catch(function (error) { if (error.response) { console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } });
With TypeScript, it is easy to find what you want with the right type.
This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.
import { AxiosResponse, AxiosError } from 'axios' axios.get('foo.com') .then((response: AxiosResponse) => { // Handle response }) .catch((reason: AxiosError) => { if (reason.response!.status === 400) { // Handle 400 } else { // Handle else } console.log(reason.message) })
Also, you can pass a parameter to both types to tell what are you expecting inside response.data
like so:
import { AxiosResponse, AxiosError } from 'axios' axios.get('foo.com') .then((response: AxiosResponse<{user:{name:string}}>) => { // Handle response }) .catch((reason: AxiosError<{additionalInfo:string}>) => { if (reason.response!.status === 400) { // Handle 400 } else { // Handle else } console.log(reason.message) })
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