
Stop Wrapping Fetch in Try/Catch — There's a Better Way
Every TypeScript developer has written this: try { const response = await fetch ( ' /api/users ' ); const users = await response . json (); } catch ( error ) { // Network error? 404? 500? Parsing error? Who knows! } The problem? HTTP errors don't throw. A 404 silently passes through. Network errors and parsing errors get lumped together. You end up with fragile, hard-to-read code. What if errors were just values? Inspired by Go's error handling, I built typed-fetch — a thin wrapper over the native Fetch API that never throws. import { typedFetch , isNetworkError , UnauthorizedError } from ' @pbpeterson/typed-fetch ' ; const { response , error } = await typedFetch < User [], UnauthorizedError > ( ' /api/users ' ); if ( error ) { if ( isNetworkError ( error )) { console . log ( ' No connection — are you offline? ' ); } else if ( error instanceof UnauthorizedError ) { console . log ( ' Session expired — redirecting to login ' ); window . location . href = ' /login ' ; } else { console . l
Continue reading on Dev.to Webdev
Opens in a new tab



