Monday, May 13, 2024
186
rated 0 times [  191] [ 5]  / answers: 1 / hits: 20769  / 6 Years ago, tue, december 4, 2018, 12:00:00

I want to be able to get the response body back from an Axios error catch.



I am using axios v0.18.0.



My axios code looks like this:



let service = axios.create({
baseURL: https://baseUrl.azurewebsites.net,
responseType: json
});

service.defaults.headers.common['authorization'] = `Bearer ${token}`;

service.post(/api/method, params).then(result => {
console.log('success',result);
}).catch(error=>{
console.log('error');
console.log(error);
});


My API call is returning a 400 error as I expected, given my inputs. So I am hitting the catch block. However I'm not able to retrieve the error message that's returned by the API call.



I've tried doing a console.out(error.response.data), but this returns null.



I've verified using Postman that the API call does return an error message in the response body, so the API isn't the problem.



What am I missing?


More From » error-handling

 Answers
21

I tested it with Mocky and the error message is indeed returned in error.response.data.



const axios = require('axios');

// http://www.mocky.io/v2/5c06f6be3000009600d25953 (the mock api to call, it always returns 400 with an error message)

let service = axios.create({
baseURL: http://www.mocky.io,
responseType: json
});

service.post(/v2/5c06f6be3000009600d25953).then(result => {
console.log('success', result);
}).catch(error => {
console.log(error.response.data);
});


The code above prints Ooops, bad request!, as returned.



EDIT: apparently the problem you described can happen for a variety of reasons. See this issue.


[#52980] Thursday, November 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;