I wanted to include some error information in my app but I'm having trouble parsing the response. I'm sending a POST
request using axios
to a remote server to transfer some file like this.
//http is an axios instance
const response = await http.post(url, formData, {
headers: {
'content-type': 'multipart/form-data',
},
});
if (response) {
return { errors: false };
} else {
return {
errors: true,
errorMessages: ['There was an error uploading the file'],
//i want to extract errors array from response actually
};
}
I can upload my file just fine and the backend seems to be validating everything as expected. So when I try to force errors sending invalid files, I see a response is coming back from the backend in the network tab of devtools that looks like this:
{"hasErrors":true,"data":false,"errors":["file extension validation: File must use .xlsx extension."]}
But in my front I can't access neither of those fields in my response
variable. The server is responding with code 400.
I appreciate any help as I'm kinda lost trying to log this and don't want to show just a generic error message when server is actually providing this information.
UPDATE
The problem was being caused by an interceptor
that the axios instance I was using had all along. The interceptor handled error responses checking what status the response was to do one thing or another, but it was doing nothing when status was 400. I just added the following code to their handler so that I could catch the exception:
if (error.response.status == 400) {
return Promise.reject(error);
};
I didn't want to mess with the way they made the axios instance so that's why I added this last piece of code to it. Another possible solution to ignore the interceptors would've been to use axios.create()
to make a new instance that doesn't have interceptors. But then I would've had to make authorization checks again. So that's why I decided to fix it this way. Now I'm able to catch the error as expected, and log it or do whatever with its information!
CodePudding user response:
The trouble here is that axios
doesn't resolve post
calls with 400-status responses; it throws an error that you can catch.
try {
const response = await http.post(/* your config */);
return {errors: false};
} catch (e) {
const {response} = e;
return {errors: true};
}
CodePudding user response:
I found the answer. Going to post it in the original comment as an update for easier reading.
The problem was being caused by an interceptor that the axios instance I was using had and this is the code I added to it, so that I could get the data I wanted. Check original post for additional information.
if (error.response.status == 400) {
return Promise.reject(error);
};