how to catch error of async call in javascript?

372 Views Asked by At

I am integrating accept.js in my app.

https://developer.authorize.net/api/reference/features/acceptjs.html

This is not particularly an integration question. This is a JavaScript problem i am trying to solve.

While following the tutorial there is a function that is called when form submit is clicked. This function is responsible for packaging the credit card information and sending it asynchronously to authorize.net server.

<script type="text/javascript">
function sendPaymentDataToAnet() {
    var authData = {};
        authData.clientKey = "YOUR PUBLIC CLIENT KEY";
        authData.apiLoginID = "YOUR API LOGIN ID";
    var cardData = {};
        cardData.cardNumber = document.getElementById("cardNumber").value;
        cardData.month = document.getElementById("expMonth").value;
        cardData.year = document.getElementById("expYear").value;
        cardData.cardCode = document.getElementById("cardCode").value;


    var secureData = {};
        secureData.authData = authData;
        secureData.cardData = cardData;

        Accept.dispatchData(secureData, responseHandler);
}
</script>

The problem is Accept.dispatchData() seems to be an async call. If i disconnect the net just before clicking on submit then Accept.dispatchData will fail to connect to the external service.

It will throw the following error

enter image description here

My goal is to catch this error. I have tried wrapping Accept.dispatchData in try catch block but it doesnt seem to catch the error thrown. Seems like the error is caught somewhere inside it. How can i detect the ERR_INTERNET_DISCONNECTED error? Thanks!

3

There are 3 best solutions below

1
Arman Charan On

window.onerror can be leveraged to detect window errors.

navigator.onLine can be used to detect internet connection.

// Window: On Error
window.onerror = (error) => console.log('navigator.onLine:', navigator.onLine)

// Trigger.
const trigger = error

0
Nitin Dhomse On

This is network connection issue, if your network is down then every javascript / jquery plugin throws this exception even Google / Facebook sites. but you can check your network before calling your api as follows.

if(navigator.onLine){
 //do your stuff
}else{
 alert("Please, check your network connection")
}
1
Ayeksius On

Use .catch()

Accept.dispatchData()
   .then(() => {})
   .catch( error => console.log(error))