1

I have a simple POST function consuming axios.post to send emails. It works fine, but I can't catch errors.

I have tried both ways with no success:

export async function postEmail(data) {
  const { subject, message, emailAddress } = data
  const body = {
    email: emailAddress,
    subject: subject,
    message: message
  }
  const url = process.env.EMAIL_API_URL
  const response = await axios.post(url, body)
  if (response.status === 200) { return response }
  else { throw 'Something wrong' }
}

And tried it with a promise:

export function postEmail(data) {
  const { subject, message, emailAddress } = data
  const body = {
    email: emailAddress,
    subject: subject,
    message: message
  }
  const url = process.env.EMAIL_API_URL
  return new Promise((resolve, reject) => {
    try {
      const response = axios.post(url, body)
      resolve(response)
    } catch (error) {
      console.log(error)
      reject(error)
    }
  })
}
4
  • axios.post returns a promise already, that's why it works as well with await. Commented Jun 15, 2021 at 17:13
  • Does this answer your question? Handling error from async await syntax with axios Commented Jun 15, 2021 at 17:14
  • Other error handling alternatives with async/await. Commented Jun 15, 2021 at 17:17
  • 1
    "have tried both ways with no success" - please show us the ways you were calling postEmail. What errors are you trying to catch, and what do you want to do with them? Commented Jun 15, 2021 at 17:22

2 Answers 2

1

I think axios already rejects if it gets something in the 4xx or 5xx range. So could that be why you are never seeing the error that you throw?

Try this for example:

let response:
try {
  response = await axios.post(url,body);
} catch (e) {
  throw new Error('Something wrong');
}

I mean, but not working, do you just mean that you are seeing the axios error rather than your error?

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

Comments

0

I solved my problem by simply removing the returned Promise and returning the values in the try catch block like so:

export async function postEmail(data){
    const emailAddress = '[email protected]'
    const {subject, message} =data
    const body = {
        email: emailAddress,
        subject: subject,
        message: message
    }
    const url = process.env.EMAIL_API_URL+4
    let response
    try {
        response = await axios.post(url,body)
        return(response)
    } catch (error) {
        console.log(error)
        return(error)
    }


}

Thank you all for pointing in the right direction.

1 Comment

You should not return error objects though

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.