API-004: Errors Must Follow Standard Response Schema
| Attribute | Value |
|---|---|
| Category | API Design |
| Default Severity | info |
| Applicable Files | Controller files (*.controller.ts, *.router.ts) |
Why It Exists (Rationale)
A standardized error response schema enables API clients, frontend applications, and API gateways to handle errors deterministically. When endpoints emit raw strings or unstructured objects upon failure:
- Client code must implement fragile regex or string comparisons to categorize errors.
- Internationalization and localized error handling become impossible.
- Automated error monitoring tools cannot group or aggregate error codes accurately.
- Machine-readable metadata (e.g., specific field validation failures, correlation IDs) is lost.
Adopting an RFC 7807 (Problem Details for HTTP APIs) or consistent structured schema ensures high predictability across all microservices.
Bad Example
// ❌ Unstructured error responses with plain string payloads
router.get("/users/:id", async (req, res) => {
const user = await userService.find(req.params.id);
if (!user) {
return res.status(404).send("User not found");
}
if (!user.isActive) {
return res.status(403).json("Account suspended");
}
return res.json(user);
});
Good Example
// ✅ Consistent structured error response
interface ApiError {
error: {
code: string;
message: string;
target?: string;
details?: Array<{ field: string; issue: string }>;
};
}
router.get("/users/:id", async (req, res) => {
const user = await userService.find(req.params.id);
if (!user) {
return res.status(404).json({
error: {
code: "USER_NOT_FOUND",
message: `No user exists with identifier ${req.params.id}`,
},
});
}
return res.json(user);
});
How It's Detected
ArchStandards scans controller methods for HTTP 4xx or 5xx status code calls followed by raw string literals in .send("...") or .json("...").
Exception Configuration
If raw string responses are required for legacy compatibility:
exceptions:
- rule: "API-004"
path: "src/controllers/legacy.controller.ts"
reason: "Legacy client protocol expects plain text responses."