Context
ADR-0002 returned bare payloads on success and RFC 7807 problem documents on failure. In use this was hard to work with: a success had no status, message or request id in the body, so debugging meant reading headers, and client code had to infer the shape from the status code.
The team's reference monorepo (silentlamp/torii-monorepo) uses { success, data, message, errors } for both outcomes, via a successResponse() helper called in each controller and a GlobalExceptionsFilter. We adopt the shape and change the mechanics.
Decision
Every response is one of two shapes, defined once in packages/shared (apiSuccessSchema, apiErrorSchema, ApiResponse<T>):
// success
{ "success": true, "statusCode": 200, "message": "Logged in", "data": { … },
"meta": { "total": 42, "page": 2, "pageSize": 20, "totalPages": 3 }, // lists only
"requestId": "…", "path": "/api/v1/auth/login", "timestamp": "…" }
// failure
{ "success": false, "statusCode": 400, "message": "Validation failed",
"errors": [{ "path": "email", "message": "Invalid email address" }], // validation only
"requestId": "…", "path": "/api/v1/auth/login", "timestamp": "…" }- Success is wrapped by a global
ResponseInterceptor, not by a helper in each controller. A handler returns its data; a list handler returns{ items, meta }. Torii's per-controller call works until one controller forgets it, and then a client meets a bare object. messagecomes from@ResponseMessage('…')on the handler, defaulting toOK.- Pagination lives under
meta, sodatais always the payload and always has one type. Torii flattenstotal/page/limitnext todata; that makes the top-level shape vary by endpoint. - Failures are wrapped by
AllExceptionsFilter. 5xx log at error with the stack; 4xx log at warn with the request id (they were at debug, so rejected requests were invisible). - No status sniffing from message text. Torii maps a 500 to 404 if the message contains "not found", to 401 if it contains "token", and so on. That turns a wording change into a status change. We only trust
HttpExceptionstatuses; everything else is a 500. 204 No Contentis not used. A 204 cannot carry a body; logout answers 200 withdata: null.
Consequences
- A client checks
successand readsdataormessage/errors— one branch, no guessing. - Every body carries
statusCode,requestId,pathandtimestamp, so a pasted response is enough to find the matching log line. - Swagger is kept honest by
@ApiEnvelope(Dto, { isArray, paginated })and@ApiErrors(...statuses)on each route (apps/api/src/common/swagger). The interceptor wraps at runtime, which the OpenAPI generator cannot see — before these decorators every route documented200: {}.test/openapi.e2e-spec.tsgenerates the document and fails if the doc classes drift from the runtime schemas inpackages/shared. - The
Content-Typeof an error is nowapplication/json, notapplication/problem+json.