📋JSON Templates

Standard API Error Response

Consistent error object structure for REST APIs following industry best practices.

Explanation

A standardized error format helps clients handle errors predictably across all endpoints.

Examples

Basic Error
Output
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      {
        "field": "email",
        "message": "Email is required"
      }
    ]
  }
}
Not Found Error
Output
{
  "error": {
    "code": "NOT_FOUND",
    "message": "Resource not found",
    "statusCode": 404
  }
}

Code Examples

TypeScript Interface
interface ApiError {
  error: {
    code: string;
    message: string;
    statusCode?: number;
    details?: Array<{
      field?: string;
      message: string;
    }>;
    timestamp?: string;
    requestId?: string;
  };
}

// Usage
const errorResponse: ApiError = {
  error: {
    code: 'VALIDATION_ERROR',
    message: 'Invalid input data',
    statusCode: 400,
    details: [
      { field: 'email', message: 'Email is required' }
    ],
    timestamp: new Date().toISOString(),
    requestId: 'req_123abc'
  }
};
Express.js Handler
// Express.js error handler middleware
app.use((err, req, res, next) => {
  const errorResponse = {
    error: {
      code: err.code || 'INTERNAL_ERROR',
      message: err.message || 'An error occurred',
      statusCode: err.statusCode || 500,
      ...(process.env.NODE_ENV === 'development' && {
        stack: err.stack
      })
    }
  };
  
  res.status(errorResponse.error.statusCode).json(errorResponse);
});

Try it Now

💡 Tips

  • Use consistent error codes across your API
  • Include field-level details for validation errors
  • Add request ID for tracking and debugging
  • Consider localization for error messages
  • Log errors server-side with full context

⚠️ Common Pitfalls

  • Don't expose sensitive information in error messages
  • Avoid stack traces in production
  • Keep error codes machine-readable (uppercase with underscores)
  • Don't use HTTP status codes as the only error indicator