← 中文资源

简体中文版本

How to Structure Error Responses for APIs

Return consistent, machine-readable error objects with a code, message, details, and request ID so clients can handle errors programmatically.

阅读英文原文

引言

A 500 with a plain text message is useless to a client. It cannot branch on the error type, it cannot show a helpful message to the user, and it cannot correlate the error with a log entry. A structured error response fixes this: it has a stable code, a human-readable message, optional details about what failed, and a request ID for correlation. This guide designs an error response schema and a handler that maps every error to it. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。

问题

When errors are ad hoc, every endpoint returns a different shape. Some return { error: “msg” }, some return { message: “msg” }, some return plain text. The client has to handle each endpoint differently, and the error messages are often generated by the framework with internal details. A consistent schema lets the client write one error handler and trust the structure. 理解问题的全貌是设计正确方案的前提。

设计决策

The error response has four fields: code, a stable machine-readable string like VALIDATION_ERROR or NOT_FOUND; message, a human-readable string safe to show to users; details, an optional object with field-level errors or constraints; and requestId, a correlation ID for log lookup. The HTTP status matches the error category: 400 for validation, 404 for not found, 409 for conflict, 500 for internal. The handler maps known errors to the schema and wraps unknown errors in an INTERNAL_ERROR with the stack trace logged but not returned. 以下代码展示了核心结构:

class ApiError extends Error {
  constructor(code, message, status, details) {
    super(message);
    this.code = code; this.status = status; this.details = details;
  }
}
const NotFound = (id) => new ApiError('NOT_FOUND', `Resource ${id} not found`, 404);
const ValidationError = (details) => new ApiError('VALIDATION_ERROR', 'Request validation failed', 400, details);

实现

The global error handler sits at the end of the middleware chain. It checks if the error is an ApiError and returns the structured response; otherwise it logs the full error with the request ID and returns a generic INTERNAL_ERROR. The request ID is generated at the start of the request and included in every error response and log entry, so a client can report the ID and the server can find the log entry. Validation errors include a details object with field names and constraint messages. 实现时需注意性能与正确性的平衡:

app.use((err, req, res, next) => {
  const requestId = req.id;
  if (err instanceof ApiError) {
    res.status(err.status).json({ code: err.code, message: err.message, details: err.details, requestId });
  } else {
    console.error('unhandled error', { requestId, err });
    res.status(500).json({ code: 'INTERNAL_ERROR', message: 'An unexpected error occurred', requestId });
  }
});

测试边界

Test that a NotFound error returns 404 with code NOT_FOUND and the resource ID in the message. Test that a ValidationError returns 400 with field-level details. Test that an unhandled error returns 500 with code INTERNAL_ERROR and no stack trace. Test that every error response includes a requestId that matches the request log. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。

常见陷阱

Avoid returning stack traces in production; they leak internal structure. Avoid using the HTTP status as the only error signal; it is too coarse for client logic. Avoid changing error codes between releases; clients depend on them. Avoid generic messages like “something went wrong” for known errors; the message should help the user or developer fix the problem. Avoid omitting the request ID; without it, errors cannot be correlated with logs. 避开这些陷阱可以减少生产事故。

结论

Structured error responses make APIs debuggable and programmable. Define a schema with code, message, details, and requestId. Map every error to it, use the HTTP status for the category and the code for the specific reason, and include a request ID for correlation. Test every error path. The result is an API where clients can handle errors confidently and operators can trace them quickly. 按照本文的方法,你可以构建出既安全又高效的解决方案。

Sources: JSON:API errors, RFC 9457 Problem Details.