今日已更新 249 条资讯 | 累计 40105 条内容
关于我们

From Contract Boundary to Error Boundary: Structuring API Error Handling in a TypeScript Frontend

Mohamad Reza Rajabi 2026年09月06日 20:38 1 次阅读 来源:Dev.to

In a previous post , I covered why TypeScript types alone can't protect you from a backend that returns something you didn't expect, and how to build a small apiRequest boundary that validates both the outgoing request and the incoming response against Zod-style schemas before your application ever touches the data. That post answered one question: Is this data actually shaped the way I think it is? It left another question open: When the answer is no, or when the request fails for a completely different reason (like a timeout or a dropped connection), what does the rest of the app do with that failure? In practice, "the rest of the app" usually does something different depending on who's writing it: One component checks error.response?.status directly. Another checks error.code === "ECONNABORTED" . A form manually digs through the error to find field-level messages. A toast just displays whatever string happens to be on error.message . The app works, but every layer speaks a different error dialect. This post is Part 2: it takes the validation boundary from Part 1 and builds the missing piece on top of it, a single, normalized ApiError shape that every layer of the app can speak, plus the logging, messaging, and form-mapping that make it actually usable. Quick Recap: The Validation Boundary From Part 1, the apiRequest wrapper validates request payloads and response bodies against schemas, and throws one of two typed errors when something doesn't match the contract: export class ApiRequestValidationError extends Error { constructor ( public readonly url : string , public override readonly cause : unknown ) { super ( `API request input does not match the contract for ${ url } .` ); this . name = " ApiRequestValidationError " ; } } export class ApiResponseValidationError extends Error { constructor ( public readonly url : string , public override readonly cause : unknown ) { super ( `API response does not match the contract for ${ url } .` ); this . name = " ApiRespon

本文内容来源于互联网,版权归原作者所有
查看原文