Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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()
        })
    })

>Solution :

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading