DEV Community

Discussion on: How to catch the body of an AXIOS error

Collapse
 
flamingo_del_khesous profile image
Triquetra • Edited

this doesn't help me, I have api that returns 400 as bad request, with a body, I can't read the body from response since the request is directly thrown to catch where there's no body!
Any suggestions please?

*Actually I found the solution: *

    ...
}).then((response) => {
    ....
}).catch((error) => {
    if( error.response ){
        console.log(error.response.data); // => the response payload 
    }
});```

Enter fullscreen mode Exit fullscreen mode
Collapse
 
mohdahmad1 profile image
Mohd Ahmad • Edited

try

JS

 try {
  // with destructuring 
  const res = await axios.get('https://example.com/someApi');

  // without destructuring 
   const res = await axios.get('https://example.com/someApi');

    return res.data;
  } catch (err) {
    console.log(`Error: ${err?.response?.data}`);
  }
Enter fullscreen mode Exit fullscreen mode

For TypeScript

 try {
  // with destructuring 
  const res = await axios.get<{ feild: type} >('https://example.com/someApi');

  // without destructuring 
   const res = await axios.get<{ feild: type} >('https://example.com/someApi');

    return res.data;
  } catch (err) {
    console.log(`Error: ${(err as AxiosError)?.response?.data}`);
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anttibull profile image
anttibull

Thank you!