跪拜 Guibai
← All articles
GitHub · Backend

Three-Layer Contract: Shape, Semantics, and Failure in Alioth's Error Handling

By 一条Go ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Error handling that mixes shape, semantics, and presentation creates bugs that are hard to trace and break frontend logic. This approach gives a concrete pattern for splitting those layers, with a pragmatic stance on message stability that many API teams will recognize.

Summary

Alioth's API error handling separates three layers that usually get tangled: shape validation via buf.validate annotations on the proto, semantic rules enforced in business code, and failure expression through the merr package. The article shows that annotations on a proto don't work until a Kratos middleware explicitly calls protovalidate; without that assembly, all min_len and lte constraints silently fail. Business validation must still repeat some length checks because non-HTTP entries (gRPC, cron, CLI) bypass the middleware, requiring constant synchronization as a deliberate cost.

The error model uses seven reasons, where Client and Invalid both map to HTTP 400 but differ in intent: Client for malformed requests, Invalid for well-formed but domain-invalid ones. That distinction lets upstream systems like the evaluator decide whether to retry or wait for user correction. A unified error format with code, reason, message, and metadata keeps machine logic and human copy separate; retryAfterSeconds goes in metadata so the frontend can drive a countdown without regexing the text.

The frontend triggers token refresh on 401 and redirects on 403 unless an allowForbidden escape hatch is set. Copy is the contract: a mapping table from backend message strings to i18n keys. The trade-off is that backend messages become frozen, new errors require paired changes, and reused messages can't have context-specific copy. Alioth accepts this for early-stage readability and suggests migrating to metadata.code for high-risk errors later. Upstream status codes must be translated, network failures wrapped as 502, and all error responses share one format so the frontend can handle them uniformly.

Takeaways
— Proto validation annotations don't take effect until a middleware explicitly calls protovalidate; missing that assembly leaves every constraint ignored.
— Business validation must repeat some proto constraints (like max length) because gRPC, cron, and CLI paths bypass HTTP middleware, requiring manual constant synchronization.
— merr distinguishes Client (malformed request) from Invalid (domain rule violation) both as 400, letting upstream auto-handle failures like the evaluator's retry logic.
— Unified error format carries code (network/log), reason (machine classification), message (user copy), and metadata (structured extras) in every response.
— Retry counters and other machine-consumable values belong in metadata, never in the message text.
— Frontend maps backend message strings to i18n keys; changing one word breaks the contract and shows raw English.
— Upstream 401/403 must be translated to platform semantics; passing them through clears sessions or sends users to irrelevant pages.
— Network fetch failures should be wrapped as 502 so list pages render standard error pages instead of raw English text.
— allowForbidden is a whitelist parameter; without it 403 always redirects, making new endpoints safe by default.
— Table-driven tests in pkg/merr/merr_test.go assert codes, reasons, and mutual exclusivity to prevent silent drift during refactors.
Conclusions

Treating human-readable messages as the contract is a deliberate early-stage trade-off: it makes errors immediately readable but freezes backend copy, and the article honestly lists the costs instead of pretending they don't exist.

The distinction between Client and Invalid shows that HTTP status codes alone are too coarse for automated retry logic; a 400 with different reasons lets upstream decide whether to retry, ignore, or alert a human.

Repeating length checks in business code to cover non-HTTP entry points highlights how middleware-centric validation creates blind spots; the cost of duplication is accepted for broader safety.

The metadata field is underused in most APIs; Alioth's example of retryAfterSeconds demonstrates how separating machine data from human copy avoids fragile regex parsing on the frontend.

Concepts & terms
buf.validate
A protobuf validation extension that lets you annotate field constraints (like gte, lte, min_len) directly in the .proto file. These annotations are syntax only until some runtime code actually invokes a validator, such as protovalidate, on the message.
merr
Alioth's error package that maps seven semantic reasons (Client, Invalid, Unauthenticated, Forbidden, NotFound, Conflict, Server) to HTTP status codes and provides helper functions like IsInvalid to let callers branch on error type.
文案即接口
A design choice where the human-readable error message string becomes the contract between backend and frontend. The frontend maintains a mapping table from message text to i18n keys; any change to the message breaks the mapping.
From the discussion
Featured comments
星云PLUS团队 1 likes

Beyond the shape and state layers, there is a category of constraints that neither side can accommodate: the precision of numeric fields. buf.validate can write gte/lte, but it cannot handle cross-field relationships such as "amount's precision must match currency" or "tax must accumulate positively when taxInclusive is false". These are neither length limits nor database state checks, so they fit better at the business use-case layer, and error codes can then land on Invalid rather than Client. As for the cost of "two constants must stay in sync" mentioned in the article, you can try generating both the proto and the business layer from the same contract constants, turning drift from a manual review issue into a codegen-time problem.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗