Handling Exceptions/Errors in TypeScript

Errors are inevitable companions in any coding journey, but in TypeScript, we can handle them appropriately and prevent them from crashing our programs.

Try/Catch: The Classic Duo

This ubiquitous duo offers a safe zone for executing risky code. Wrap the potentially problematic sections in a try block. If an error occurs, it's thrown and caught in the catch block, allowing you to handle it smoothly:

try { const age = parseInt(userInput); if (isNaN(age)) { throw new Error("Invalid age entered!"); } console.log(`You are ${age} years old.`); } catch (error) { console.error(error.message); // Display a user-friendly error message. }

Typescript Errors: Customizing the Experience

Instead of generic Error objects, TypeScript allows you to define custom error types with specific properties and messages:

class AgeError extends Error { constructor(message: string) { super(message); this.name = "AgeError"; } } try { // Same logic as before... } catch (error) { if (error instanceof AgeError) { console.error("Please enter a valid number for your age."); } else { console.error("An unexpected error occurred."); } }

Async/Await and Error Handling

Even asynchronous code needs error handling. Use try/catch within async functions to catch errors thrown during asynchronous operations:

async function fetchData(url: string): Promise<string> { try { const response = await fetch(url); const data = await response.json(); return data; } catch (error) { console.error(`Error fetching data: ${error.message}`); return null; } }

TypeScript Type Annotations for Errors

function throwError(): never { throw new Error("This function never returns a value."); } try { throwError(); } catch (error: any) { // 'error' is implicitly of type 'any', but TypeScript allows more specific typing console.error(`Caught an error: ${error.message}`); }

TypeScript's type system allows developers to provide more specific types for errors caught in the catch block. In this example, the error parameter is implicitly of type any, but developers can provide a more precise type if they know the structure of the error.

Conclusion

TypeScript Error Handling involves the use of try, catch, and finally blocks to manage and respond to errors during code execution. Developers can create custom error classes, utilize TypeScript type annotations for more precise error handling, and extend error-handling techniques to asynchronous operations using Promises for building resilient and reliable applications.