Monday, May 20, 2024
91
rated 0 times [  96] [ 5]  / answers: 1 / hits: 119959  / 6 Years ago, wed, january 17, 2018, 12:00:00

for e.g.



(async() => {
let apiRes = null;
try {
apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
} catch (err) {
console.error(err);
} finally {
console.log(apiRes);
}
})();


in finally, apiRes will return null.



Even when the api get a 404 response, there is still useful information in the response that I would like to use.



How can I use the error response in finally when axios throws error.



https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/


More From » error-handling

 Answers
51

According to the documentation, the full response is available as a response property on the error.



So I'd use that information in the catch block:



(async() => {
let apiRes = null;
try {
apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
} catch (err) {
console.error(Error response:);
console.error(err.response.data); // ***
console.error(err.response.status); // ***
console.error(err.response.headers); // ***
} finally {
console.log(apiRes);
}
})();


Updated Fiddle



But if you want it in finally instead, just save it to a variable you can use there:



(async() => {
let apiRes = null;
try {
apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
} catch (err) {
apiRes = err.response;
} finally {
console.log(apiRes); // Could be success or error
}
})();

[#55438] Saturday, January 13, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
;