PromptBase
PromptBase SelectGet Select
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Prompt Details

Model
Chat - (gpt-5.6)
Token size
2,816
Example input
[API_AND_BACKEND_ARCHITECTURE]: Node.js + Express + PostgreSQL backend. Architecture: API Gateway → Express Middleware → Controllers → Services → Repositories → PostgreSQL Some services call Stripe and an internal Inventory Service. A global error middleware exists, but several controllers also use local try/catch blocks. [API_ROUTES_CONTROLLERS_AND_HANDLERS]: POST /api/orders GET /api/orders/:id POST /api/payments PATCH /api/users/:id GET /api/products/:id Controllers use mixed error-handling patterns. Some return errors directly. Some throw exceptions. Some convert exceptions to HTTP responses locally. [EXCEPTION_CLASSES_AND_ERROR_HANDLING_CODE]: ValidationError UnauthorizedError ForbiddenError NotFoundError ConflictError PaymentError DatabaseError Global handler: ValidationError → 400 UnauthorizedError → 401 ForbiddenError → 403 NotFoundError → 404 Everything else → 500 Some controllers catch database errors and return: 500 + err.message [TESTS_LOGS_AND_ERROR_RESPONSES]: Tests mainly verify HTTP status codes. Few tests verify error-body structure. Logs sometimes contain: user email order ID database error Stripe error message No consistent correlation/request ID. Example response: 500 { "message": "duplicate key value violates unique constraint users_email_key" } [CLIENT_COMPATIBILITY_AND_ERROR_REQUIREMENTS]: Mobile and web clients consume the API. Clients currently inspect HTTP status codes. Some clients also inspect message text. Clients need to know whether they should: - fix input - login again - retry - stop retrying - show an error
Example output
Phase 1: API Error Architecture Reconstruction Current observed flow Request ↓ API Gateway ↓ Express Middleware ↓ Authentication ↓ Validation ↓ Controller ↓ Service ↓ Repository / External Service ↓ Exception ↓ Local try/catch OR Global Error Handler ↓ HTTP Response ↓ Client Major architectural issue There are two error-mapping systems: Controller-level mapping + Global error mapping This creates inconsistent behavior. For example: Database error ↓ Controller A ↓ 500 + database message Database error ↓ Controller B ↓ Global handler ↓ 500 + generic message The same internal failure can therefore produce different public responses. Risk High Clients cannot reliably determine whether two apparently different errors represent the same failure category. --- Phase 2: HTTP Status Code Audit Finding 1: Validation errors Current ValidationError → 400 Expected 400 Bad Request This is acceptable if the API consistently uses 400 for syntactically/semantically invalid request input. However, the response structure is inconsistent. Client impact The client knows the request failed, but cannot reliably parse which fields failed because different endpoints use different schemas. Severity: Medium --- Finding 2: Authentication Current Missing/invalid JWT → 401 Expected 401 Unauthorized Correct. However, the API should use a stable error code such as: AUTHENTICATION_REQUIRED or INVALID_AUTHENTICATION instead of making clients depend on message text. Severity: Low --- Finding 3: Authorization Current Insufficient permission → 403 Expected 403 Forbidden Correct. But protected-resource access sometimes returns 404. This needs to be intentional. For example: GET /orders/123 If order 123 exists but belongs to another user, returning: 403 reveals that the resource exists. Returning: 404 can intentionally hide resource existence. Recommendation For resources where existence must not be disclosed: 404 RESOURCE_NOT_FOUND For ordinary authorization failures where existence is already known: 403 FORBIDDEN The choice should be documented and consistent. Severity: High --- Phase 3: Exception-to-HTTP Mapping Audit Current mapping: ValidationError → 400 UnauthorizedError → 401 ForbiddenError → 403 NotFoundError → 404 ConflictError → 409 Unknown exception → 500 The basic taxonomy is reasonable, but important mappings are missing. Recommended mapping Internal condition HTTP Error code Invalid request 400 INVALID_REQUEST Validation failure 400 VALIDATION_FAILED Missing authentication 401 AUTHENTICATION_REQUIRED Invalid authentication 401 INVALID_AUTHENTICATION Permission denied 403 FORBIDDEN Resource unavailable/hidden 404 RESOURCE_NOT_FOUND Resource conflict 409 RESOURCE_CONFLICT Rate limited 429 RATE_LIMITED Request timeout 408/504* REQUEST_TIMEOUT / UPSTREAM_TIMEOUT Dependency unavailable 503 DEPENDENCY_UNAVAILABLE Unexpected server failure 500 INTERNAL_ERROR 408 vs 504 depends on whether the API server timed out waiting for the client versus an upstream dependency. --- Phase 4: Error Schema Consistency Audit This is one of the largest problems in the sample. Current responses include: { "message": "Something went wrong" } and: { "error": "Invalid request", "fields": { "email": "Invalid email" } } and: { "status": "failed", "reason": "Card declined" } These are three incompatible contracts. Client problem A client must implement: if response.error exists... else if response.message exists... else if response.reason exists... This creates fragile client logic. --- Recommended Canonical Error Schema Use one schema across the API: { "error": { "code": "VALIDATION_FAILED", "message": "The request contains invalid fields.", "request_id": "req_01JXYZ123", "details": [ { "field": "email", "code": "INVALID_FORMAT", "message": "Email address is invalid." } ] } } Required fields error.code error.message error.request_id Optional error.details error.documentation_url error.retry_after The machine-readable field is: code The human-readable field is: message Clients should primarily depend on code. --- Phase 5: Internal Error Leakage Analysis Critical finding This response is unsafe: { "message": "duplicate key value violates unique constraint users_email_key" } It exposes database implementation details. Potentially exposed information includes: Database engine behavior Constraint names Database schema information Implementation details Another risky pattern catch (err) { return res.status(500).json({ message: err.message }); } This should not be allowed in production API handlers. Recommended behavior Client: { "error": { "code": "INTERNAL_ERROR", "message": "An unexpected error occurred.", "request_id": "req_01JXYZ123" } } Internal log: request_id=req_01JXYZ123 exception=DatabaseError constraint=users_email_key stack_trace=... The diagnostic information stays internal. Severity: Critical --- Phase 6: Validation Error Audit Current stack: Joi + Zod This is not automatically wrong, but it creates different validation error structures. Example A { "error": "Invalid request", "fields": { "email": "Invalid email" } } Example B Potentially: { "message": "Expected string, received number" } Recommended normalized output { "error": { "code": "VALIDATION_FAILED", "message": "The request contains invalid fields.", "request_id": "req_123", "details": [ { "field": "email", "code": "INVALID_FORMAT", "message": "Email address is invalid." }, { "field": "quantity", "code": "INVALID_TYPE", "message": "Quantity must be an integer." } ] } } This allows clients to render field-level errors consistently. --- Phase 7: Authentication & Authorization Audit Scenario 1: No JWT Expected: 401 AUTHENTICATION_REQUIRED Scenario 2: Invalid JWT Expected: 401 INVALID_AUTHENTICATION Scenario 3: Valid JWT but insufficient permission Expected: 403 FORBIDDEN Scenario 4: User requests another user's hidden resource Potentially: 404 RESOURCE_NOT_FOUND This should be an explicit security policy rather than an accidental inconsistency. Security recommendation Never return: "Order 123 exists but belongs to another user." That can create an object-enumeration vulnerability. Severity: High --- Phase 8: Downstream Error Mapping The payment provider returns: Card declined The API should not automatically expose the provider's raw response. Bad: { "message": "Stripe API: card_declined, payment_intent=pi_123..." } Better: { "error": { "code": "PAYMENT_DECLINED", "message": "The payment could not be completed.", "request_id": "req_123" } } Internal logs can contain the provider-specific diagnostic information. --- Dependency failure Suppose Inventory Service is unavailable. Do not return: 500 INTERNAL_ERROR if the actual problem is a dependency outage. Prefer: 503 SERVICE_UNAVAILABLE with: DEPENDENCY_UNAVAILABLE This gives clients better retry semantics. --- Phase 9: Client Behavior Consistency The API should establish clear client behavior. Error Client action 400 Fix request 401 Refresh/login 403 Stop retrying 404 Treat resource as unavailable 409 Resolve conflict 429 Wait and retry 500 Limited retry/backoff 503 Retry with backoff Timeout Retry according to idempotency rules Current problem Because clients inspect message text, this is dangerous: "Card declined" "Your card was declined" "Payment failed" "Payment unsuccessful" All may represent the same condition. Clients should instead inspect: PAYMENT_DECLINED --- Phase 10: Error Message & Error Code Audit Current Messages are being used as identifiers. Example: "Card declined" Problem Changing wording can silently break clients. Bad: if (error.message === "Card declined") { ... } Recommended { "code": "PAYMENT_DECLINED", "message": "The payment could not be completed." } The message can evolve. The code remains stable. --- Phase 11: Logging & Observability Audit Current logs include: email order ID database error Stripe error Potential issue: sensitive information may be logged without a defined policy. Recommended structured log { "timestamp": "...", "level": "ERROR", "request_id": "req_123", "route": "POST /api/orders", "error_code": "DATABASE_CONSTRAINT_ERROR", "exception": "UniqueConstraintViolation", "service": "order-service", "duration_ms": 245 } Do not log: Passwords JWTs Authorization headers Payment secrets API keys Full sensitive payloads --- Phase 12: Error Handling Failure Modes Failure Mode 1: Error handler throws Example: Database failure → error handler → serializer fails → no valid JSON response Severity: Critical Global handler must itself be defensive. --- Failure Mode 2: Local handler bypasses global handler Controller catch → res.status(500) This creates inconsistent behavior. Severity: High --- Failure Mode 3: Error logged multiple times Repository logs → Service logs → Controller logs → Global handler logs One failure can create four alerts. Recommendation: Log once at the appropriate ownership boundary. Add context as errors propagate rather than repeatedly logging the same exception. --- Failure Mode 4: Unknown exception leaks Any code path doing: res.status(500).json({ message: error.message }) can expose internal information. Severity: Critical --- Phase 13: Standardized Error Architecture Recommended architecture: INTERNAL FAILURE ↓ Exception Classification ↓ Domain Exception ↓ Error Mapping Layer ↓ ┌─────────────┴─────────────┐ ↓ ↓ HTTP Status Error Code ↓ ↓ └─────────────┬─────────────┘ ↓ Sanitization Layer ↓ Canonical Error Schema ↓ API Response ↓ Client Parallel diagnostic path: Exception ↓ Structured Logger ↓ Request/Correlation ID ↓ Metrics ↓ Tracing ↓ Alerting --- Recommended Exception Hierarchy AppError │ ├── ClientError │ ├── ValidationError │ ├── AuthenticationError │ ├── AuthorizationError │ ├── NotFoundError │ ├── ConflictError │ └── RateLimitError │ ├── DomainError │ ├── PaymentDeclinedError │ ├── InsufficientInventoryError │ └── OrderStateError │ ├── DependencyError │ ├── DatabaseError │ ├── PaymentProviderError │ ├── InventoryServiceError │ └── StorageError │ └── InternalError --- Phase 14: Implementation Rules Rule 1 Controllers should not independently design error responses. Use: throw exception → global mapper → canonical response --- Rule 2 Never do this: res.status(500).json({ message: err.message }); --- Rule 3 Every public error must have a stable code. Example: VALIDATION_FAILED AUTHENTICATION_REQUIRED FORBIDDEN RESOURCE_NOT_FOUND RESOURCE_CONFLICT PAYMENT_DECLINED RATE_LIMITED DEPENDENCY_UNAVAILABLE INTERNAL_ERROR --- Rule 4 Human-readable messages must never be the primary client contract. --- Rule 5 Every error response should contain a request/correlation identifier. --- Rule 6 Unknown exceptions must always have a safe fallback. HTTP 500 + INTERNAL_ERROR + generic client-safe message + request ID --- Rule 7 Downstream errors must be translated into API-level errors. StripeError ≠ Public API error DatabaseError ≠ Public API error --- Phase 15: Automated Error Test Strategy Test 1: Missing required field INPUT POST /orders body = {} EXPECTED STATUS 400 EXPECTED ERROR CODE VALIDATION_FAILED EXPECTED SCHEMA error.code error.message error.request_id error.details SECURITY No stack trace. CLIENT Correct the request. --- Test 2: Invalid JWT INPUT Authorization: Bearer invalid-token STATUS 401 CODE INVALID_AUTHENTICATION CLIENT Authenticate again. SECURITY Do not expose JWT parsing internals. --- Test 3: Insufficient permission INPUT Authenticated user requests admin operation. STATUS 403 CODE FORBIDDEN CLIENT Do not retry unchanged request. --- Test 4: Hidden resource INPUT User requests another user's order. STATUS 404 CODE RESOURCE_NOT_FOUND SECURITY Do not reveal whether the resource exists. --- Test 5: Duplicate email INPUT POST /users with existing email STATUS 409 CODE RESOURCE_CONFLICT CLIENT Resolve conflict/change email. The database constraint name must not be exposed. --- Test 6: Payment declined INPUT Payment provider returns card_declined. STATUS 402 or documented domain-specific response CODE PAYMENT_DECLINED CLIENT Ask user for another payment method. SECURITY Do not expose provider internals. --- Test 7: Rate limit INPUT Exceed API rate limit. STATUS 429 CODE RATE_LIMITED CLIENT Wait before retrying. OPTIONAL Retry-After information. --- Test 8: Database outage INPUT Database connection unavailable. STATUS 503 CODE DEPENDENCY_UNAVAILABLE CLIENT Retry with exponential backoff where safe. SECURITY No connection string or database error. --- Test 9: Unexpected exception INPUT Force unhandled runtime exception. STATUS 500 CODE INTERNAL_ERROR CLIENT Generic failure handling. SECURITY No stack trace. No file path. No SQL. No exception name. LOGGING Full internal diagnostic information. --- Phase 16: Final Audit Report Executive Summary Overall health: 5/10 - Needs significant standardization The backend has the basic foundations of error handling, but error behavior is not yet a reliable API contract. Biggest problems 1. Multiple error-response schemas. 2. Controller-level and global error mapping are both used. 3. Database errors can leak directly to clients. 4. Clients depend on message text. 5. No consistent request/correlation ID. 6. Validation responses differ between libraries/endpoints. 7. Downstream failures are not consistently translated. 8. Error-body structures have limited automated coverage. --- 🚦 Status Code Findings Finding Severity Mixed 403/404 authorization behavior High Dependency failures potentially represented as 500 High Missing 429 standardization Medium Missing timeout classification Medium Validation status generally acceptable Low --- 🧩 Exception Mapping Findings High priority Raw DatabaseError → public response must become: DatabaseError → sanitized Dependency/Internal classification → stable API error Recommended principle Internal exception ↓ Classification ↓ Public error mapping Never: Internal exception ↓ err.message ↓ Client --- 📋 Error Schema Findings Current message error fields status reason Target { "error": { "code": "...", "message": "...", "request_id": "...", "details": [] } } One public contract should be used across endpoints. --- 🛡️ Security Findings Critical Database error leakage duplicate key value violates unique constraint... must never reach clients. High Resource enumeration risk Inconsistent 403/404 behavior may reveal protected-resource existence. High Potential sensitive logging Define structured logging and redaction policies. --- 🔄 Client Behavior Findings The biggest client compatibility issue is: Clients depend on messages. Replace: if message == "Card declined" with: if code == "PAYMENT_DECLINED" This makes the API much more stable. --- 📊 Observability Findings Current gaps: No consistent request ID No standardized error categories Inconsistent structured logging Potential sensitive data exposure Weak error metrics Limited failure-path testing Recommended metrics: errors_total errors_by_code errors_by_endpoint errors_by_status dependency_errors validation_errors 5xx_rate 429_rate timeout_rate --- 🏗️ Target Architecture Request ↓ Middleware ↓ Authentication/Validation ↓ Controller ↓ Service ↓ Repository/Dependencies ↓ Exception ↓ Error Classifier ↓ Error Mapper ↓ Sanitization ↓ Canonical Schema ↓ Client And simultaneously: Exception ↓ Structured Logging ↓ Request ID ↓ Metrics ↓ Tracing ↓ Alerting --- 🛣️ Migration Roadmap 0-30 Days Priority: Security + immediate consistency 1. Stop exposing err.message. 2. Remove database error leakage. 3. Add global fallback handler. 4. Introduce request IDs. 5. Define initial error-code catalog. 6. Standardize 401/403/404 behavior. 7. Add tests for 500 responses and information leakage. 31-90 Days Priority: Contract standardization 1. Introduce canonical error schema. 2. Normalize Joi/Zod validation errors. 3. Centralize exception-to-HTTP mapping. 4. Translate downstream exceptions. 5. Add 409/429/503 semantics. 6. Update API documentation. 7. Add contract tests. 8. Update web/mobile clients to use error codes. 3-6 Months Priority: Enterprise enforcement 1. Apply error architecture across services. 2. Introduce centralized error-code registry. 3. Add distributed tracing. 4. Add error dashboards. 5. Add automated schema validation. 6. Add static/code-review rules against raw err.message responses. 7. Monitor backward compatibility. 8. Deprecate legacy error formats. --- 🎯 Final Recommendation The highest-impact change is to stop treating individual error responses as controller-specific implementation details and establish a single API-wide contract: Exception → Classification → Mapping → Sanitization → Canonical Error Schema → Client The target client contract should be: { "error": { "code": "PAYMENT_DECLINED", "message": "The payment could not be completed.", "request_id": "req_123", "details": [] } } The core principle is: Stable code for machines + Safe message for humans + Request ID for support + Detailed diagnostics only internally That combination gives the API predictable client behavior, stronger security, easier debugging, and safer long-term API evolution.
GPT

Api Error Handling Consistency Auditor

Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
GPT-5.6
Tested icon
Guide icon
4 examples icon
Free credits icon
Inconsistent API errors create unpredictable client behavior, expose internal details, and make backend systems harder to debug and maintain. 🔍 Audit API error-handling patterns 🚦 Detect incorrect/inconsistent status codes 🛡️ Find leaked internal errors 📋 Identify missing error schemas 🔄 Analyze exception-to-HTTP mapping 🧩 Standardize client-facing behavior 🧪 Generate automated error test scenarios 🏗️ Design a consistent error architecture Turn inconsistent backend errors into a predicta
...more
Added over 1 month ago
Report
Browse Marketplace