TypeScript:
Handling errors
How to:
In TypeScript, handling errors often involves try
, catch
, and finally
blocks.
function riskyOperation() {
throw new Error("Something went wrong!");
}
function handleErrors() {
try {
riskyOperation();
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("This always runs, error or not.");
}
}
handleErrors();
Sample output:
Caught an error: Something went wrong!
This always runs, error or not.
Async example with promises:
async function asyncRiskyOperation() {
return new Promise((resolve, reject) => {
// Simulate an error
reject("Failed miserably");
});
}
async function handleAsyncErrors() {
try {
await asyncRiskyOperation();
} catch (error) {
console.error("Caught async error:", error);
}
}
handleAsyncErrors();
Sample output:
Caught async error: Failed miserably
Deep Dive
Error handling has been a cornerstone of programming since its inception. In TypeScript, which builds on JavaScript, error handling became more robust with the introduction of async/await in ECMAScript 2017. Before that, we often relied on callback functions and promises to handle errors in asynchronous code.
An alternative to try/catch
in TypeScript is using error boundaries provided by frameworks like React. For server-side handling, we can use middleware in platforms like Express.js to centralize error management.
Implementation-wise, TypeScript doesn’t have its own error handling mechanism but relies on JavaScript’s. Custom error classes can extend the Error
class to offer more descriptive error information.