Javascript how to catch an error and also have .then() on the same function

Viewed 19

The problem is that .then() (to show success message) doesn't work if axios gets an error, so I want to have .catch() to show an error, but if the axios request does work, I want it to show a succes message

How do I write this function so it would .catch() errors and also have .then()?

I want to add this piece of code:

.then(() => 
            {
                swal({
                    title: "Message sent successfully!",
                    type: "success" 
                }).then(function(){
                    location.reload()
                })
            })

To this function:

axios.post('http://localhost:5291/api/Mail', {
        "to": url,
        "subject": document.getElementById("ContactSubject").value,
        "body": `<h3>From:</h3> ${document.getElementById("ContactEmail").value} <br>
                 <h4>Name:</h4> ${document.getElementById("ContactName").value} <br>
                 <h4>Message:</h4> ${document.getElementById("ContactMessage").value}`
    }).catch((error)=> {
        swal("Something went wrong!" , `${error.message}` , "error")
        .then(function(){
            location.reload()
        })
    })
1 Answers

You can totally do both:

axios.post(...)
  .then(res => alert('Success'))
  .catch(err => alert('Error'))

And if you want to do something in both success & error cases, you can add finally clause like this:

axios.post(...)
  .then(res => alert('Success'))
  .catch(err => alert('Error'))
  .finally(() => alert('Processed'))
Related