1

I'm making an API request using the async/await pattern in a try/catch block..

async myRequest(data) {

  try {

    await api.post('/my-endpoint/', data).then((response) => { 

        console.log(response.data)
    });

  } catch (ex) {

     // WANT TO READ RESPONSE DATA HERE
  }
}

If the request succeeds without errors, I am able to read the response with the .then() method.

If the request fails, this API returns a 422 code that triggers the try/catch exception.

However, if the request fails, this API still returns some data in the response body that I would like to to read but unable to because catch is triggered and .then() is never run.

How can I get the response body from the async function within the catch block?

3 Answers 3

4

Try this if you are on Axios lib:

catch (e) {
  console.log(e.response.data);
}

console.log uses the toString method to format Error objects so it is hard to find the response property if you only log e (error). Docs: https://axios-http.com/docs/handling_errors

Sign up to request clarification or add additional context in comments.

Comments

0

The error object is stored in ex so you can log the error with } catch (ex) { console.log(ex) } One of the problems you are making is putting the .then after you call your API. When you are using the try-catch block you don't need to do the then because you can save the result into a variable.

One of the benefits of the try-catch block is that the errors are handled and you can do multiple async calls

async myRequest(data) {

  try {

    const response = await api.post('/my-endpoint/', data)
    console.log(response.data)
  } catch (ex) {

     console.log(ex)
  }
}

Comments

0

If you want to retrieve the response data from a catch block, you can do it technically.

See the following code.

const myRequest = async () => {
    try {
      const data = await fetch('https://jsonplaceholder.typicode.com/xxx/1').then((result)=> {
     

       // You can change the status code to 422 
       if (result.status === 404) {
         throw new Error('You can put your data here.')
         // Make sure the argument you passed in Error is a string 
       }

      return result.json()
    })
      
    } catch(e){
      console.log(e.message);
    }
}

myRequest()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.