Handling callback errors

In this section, we are going to explore how we can handle errors when using callback code:

  1. Let's start by entering the following code in the TypeScript playground:
try {
setTimeout(() => {
throw new Error("Something went wrong");
}, 1000);
} catch (ex) {
console.log("An error has occurred", ex);
}

We are again using setTimeout to experiment with callbacks. This time, we throw an error inside the callback. We are hoping to catch the error outside the callback using a try / catch around the setTimeout function.

If we run the code, we see that we don't catch the error:

  1. We must handle errors within the callback. So, let's adjust our example to the following:
interface IResult {
success: boolean;
error?: any;
}
let result: IResult = { success: true };
setTimeout(() => {
try {
throw new Error("Something went wrong");
} catch (ex) {
result.success = false;
result.error = ex;
}
}, 1000);
console.log(result);

This time, the try / catch is within the callback. We use a variable, result, to determine whether the callback was executed successfully, along with any error. The IResult interface gives us a nice bit of type safety with the result variable.

If we run this code, we'll see that we successfully handle the error:

So, handling errors along with reading callback-based code is a challenge. Luckily, there are alternative approaches that deal with these challenges, which we'll go through in the next sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.139.169