Better Error Handling

https://news.ycombinator.com/rss Hits: 11
Summary

Bad error handling has cost billions of dollars, crashed planes, killed people, tanked stock markets, wrecked vehicles, and delayed flights. As we reflect on Halloween, it’s fitting to consider these horror stories of software gone wrong. You can read more about them in my A Halloween scary story, based on true events, or watch this newly minted Fireship video. VIDEO Thank God I didn’t fly during the CrowStrike incident (see what I did there?). Error handling isn’t just a technical challenge - it’s a critical aspect of software safety and reliability. Yet in TypeScript and JavaScript, it remains something of a wild west. Today, I’ll share an overview of the current landscape and my preferred approaches. The Current State of Error Handling The most common approach is the traditional try/catch method. Everyone is familiar with its basic syntax, which works similarly for both synchronous and asynchronous code: async function fetchUserDataBasic(userId: number): Promise<UserData> { try { const profile = await fetchProfileRaw(userId); const posts = await fetchPostsRaw(userId); return { id: userId, profile, posts }; } catch (error) { throw new Error(`Failed to fetch user data: ${error.message}`); } } While this works well for simple scenarios, it presents significant challenges when scaled to enterprise-level applications or complex libraries. For the sake of comparison later with other alternative, let’s consider the scenarios of API Request Chain with Rate Limiting. Consider calling multiple dependent APIs where you need to: Handle rate limit errors specially (by waiting and retrying). Aggregate errors from multiple calls. Transform upstream service errors into your API’s error format. Preserve the original error context for debugging. The code would look somewhat like this: // Traditional try/catch approach type UserData = { id: number; profile: string; posts: string[]; }; type ApiError = { type: 'RateLimit' } | { type: 'NetworkError'; message: string }; // Traditional ...

First seen: 2025-04-20 22:28

Last seen: 2025-04-21 09:34