How To Handle Errors in Asynchronous Javascript Code (when working with Callbacks)
We will use a simple function called calculateSquare to demonstrate how to handle errors in asynchronous Javascript code.
In order to simulate an asynchronous function, we will use setTimeout:
function calculateSquare(number, callback) {
setTimeout(() => {
const result = number * number;
callback(result);
}, 1000);
}
// callback function that logs out the result of calculateSquare
let callback = (result) => {
console.log('Result from calculateSquare: ' + result)
}// calling calculateSquare with input as the number with value of 2calculateSquare(2, callback);
Run the code above and everything works:
But what happens when this function gets a String instead of a Number type?
// calling the function with input as a String with value of "two"
calculateSquare("two", callback);
// Result
Result from calculateSquare: NaN
We would get NaN (not a number) for the result. This needs to be handled.
We add on number type validation below, which throws an error if the input is not a number:
// modified function to include number type validation (in bold)
function calculateSquare(number, callback) {
setTimeout(() => { if (typeof number !== "number") {
throw new Error("Argument of type number is expected.");
return;
} const result = number * number;
callback(null, result);
}, 1000);
}let callback = (result) => {
console.log('Result from calculateSquare: ' + result)
}
For error handling, lets try to wrap the function call in a try-catch statement, where errors are typically expected to be “caught” in the catch block (not always, as we will see soon). If we run the above code again with the input as a string..
// calling the function with input as a String with value of "two"
try {
calculateSquare("two", callback);
} catch…