Coding
api
error-handling
rest

API Error Handler Generator

Generate consistent, user-friendly API error handling with proper HTTP status codes, error schemas, and logging.

The Prompt

(2 messages)
System
You are a backend engineer who specializes in API design. Generate robust error handling code that is consistent, informative for clients, and safe for production.

Guidelines:
- Map errors to correct HTTP status codes (400, 401, 403, 404, 409, 422, 429, 500)
- Return a consistent error response shape: { error: { code, message, details? } }
- Never leak internal details (stack traces, SQL queries, file paths) in production responses
- Log the full error internally for debugging
- Handle both expected errors (validation, not found) and unexpected errors (crashes, timeouts)
- Include request ID for correlation between client reports and server logs
- Generate for the specified framework and language
User
Generate error handling for:

Framework: {{framework}}
Error scenarios: {{scenarios}}
Requirements: {{requirements}}

Variables

Fill in these inputs to customize your output:

{{framework}}

Example: Express.js with TypeScript

{{scenarios}}

Example: validation errors, not found, duplicate resource, unauthorized, rate limiting, internal server error

{{requirements}}

Example: Central error handler middleware, custom error classes, request ID tracking, JSON error responses

Example Output

Here's what this prompt generates with the sample inputs:

Sample outputgpt-4.1
// --- Custom Error Classes ---

class AppError extends Error {
  constructor(
    public statusCode: number,
    public code: string,
    message: string,
    public details?: unknown
  ) {
    super(message)
    this.name = 'AppError'
  }
}

class ValidationError extends AppError {
  constructor(details: Record<string, string>) {
    super(422, 'VALIDATION_ERROR', 'Request validation failed', details)
  }
}

class NotFoundError extends AppError {
  constructor(resource: string) {
    super(404, 'NOT_FOUND', resource + ' not found')
  }
}

class ConflictError extends AppError {
  constructor(message: string) {
    super(409, 'CONFLICT', message)
  }
}

class UnauthorizedError extends AppError {
  constructor(message = 'Authentication required') {
    super(401, 'UNAUTHORIZED', message)
  }
}

class RateLimitError extends AppError {
  constructor(retryAfter: number) {
    super(429, 'RATE_LIMITED', 'Too many requests', { retry_after: retryAfter })
  }
}

// --- Error Handler Middleware ---

function errorHandler(err: Error, req: Request, res: Response, _next: NextFunction) {
  const requestId = req.headers['x-request-id'] || crypto.randomUUID()

  if (err instanceof AppError) {
    // Expected errors — log at warn level
    logger.warn({ requestId, code: err.code, message: err.message })

    return res.status(err.statusCode).json({
      error: {
        code: err.code,
        message: err.message,
        ...(err.details && { details: err.details }),
        request_id: requestId,
      },
    })
  }

  // Unexpected errors — log full stack, return generic message
  logger.error({ requestId, error: err.message, stack: err.stack })

  return res.status(500).json({
    error: {
      code: 'INTERNAL_ERROR',
      message: 'An unexpected error occurred',
      request_id: requestId,
    },
  })
}

Configuration

Optimized settings included when you add this prompt. You can adjust them later.

Provider

OPENAI

Model

gpt-4.1

Temperature

0.2

Ready to use this prompt?

Add it to your workspace, customize the inputs, and generate your own results.

Use this prompt — free

More prompts