Designing API Error Codes and Messages: Best Practices and Standardization
This article explains how to design clear, consistent API error codes and messages by referencing HTTP status code segmentation, defining code‑message pairs, customizing user‑friendly messages, and centralizing handling to improve communication, debugging, and monitoring for backend services.
In modern client‑server interactions, APIs rely on return codes to indicate whether a request succeeded and to guide subsequent processing. Inconsistent or ambiguous code definitions—such as mixing integer and string types, or using different values for success—create confusion and increase maintenance costs.
HTTP Status Code Reference
Using the well‑known HTTP status code ranges as a model, the article shows how 2XX codes (e.g., 200) represent success, while 5XX codes (e.g., 502) indicate server errors, illustrating how segmented codes help quickly diagnose issues.
Parameter Conventions
Beyond a numeric code , each error should include a human‑readable message so developers can understand the problem. By segmenting error codes (similar to HTTP), the design enables both programs and people to distinguish results easily.
Personalized Messages
While engineers need precise messages, end‑users often require friendlier wording. For example, error codes 20001 and 20002 both indicate order‑creation failures but can be translated into a single user‑facing prompt like “You have an ongoing order; please check your order list.”
Storing these localized messages in a database or cache (e.g., Redis) allows the API to replace the generic message with a context‑specific one at runtime.
This approach lets mobile apps, mini‑programs, and web portals display different messages for the same underlying error code.
Unified Handling of Return Information
With a standardized code , monitoring tools (NGINX, APM) can aggregate request counts per code, trigger alerts for high‑frequency error codes (e.g., 99999), and generate visual reports to pinpoint systemic or business‑logic problems.
Overall, a well‑designed error‑code system reduces communication overhead, simplifies debugging, and lowers long‑term maintenance costs.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.