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)
    }
  })
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Ergun
  • 458
  • 1
  • 8
  • 21
  • `axios.post` returns a promise already, that's why it works as well with `await`. – Emile Bergeron Jun 15 '21 at 17:13
  • Does this answer your question? [Handling error from async await syntax with axios](https://stackoverflow.com/questions/52512065/handling-error-from-async-await-syntax-with-axios) – Emile Bergeron Jun 15 '21 at 17:14
  • Other [error handling alternatives with `async/await`](https://stackoverflow.com/q/40884153/1218980). – Emile Bergeron Jun 15 '21 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? – Bergi Jun 15 '21 at 17:22

2 Answers2

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?

Alex028502
  • 3,486
  • 2
  • 23
  • 50
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 = 'ergun@atlaspet.com.tr'
    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.

Ergun
  • 458
  • 1
  • 8
  • 21