[{"data":1,"prerenderedAt":317},["ShallowReactive",2],{"blog-prompts/add-error-handling":3},{"id":4,"title":5,"body":6,"category":296,"date":297,"dateModified":298,"description":299,"draft":300,"extension":301,"faq":302,"featured":300,"headerVariant":303,"image":302,"keywords":302,"meta":304,"navigation":305,"ogDescription":306,"ogTitle":302,"path":307,"readTime":302,"schemaOrg":308,"schemaType":309,"seo":310,"sitemap":311,"stem":312,"tags":313,"twitterCard":315,"__hash__":316},"blog/blog/prompts/add-error-handling.md","Add Secure Error Handling with AI Prompts",{"type":7,"value":8,"toc":287},"minimark",[9,16,21,24,49,53,56,92,102,106,109,160,164,167,208,217,233,237,240,261,275],[10,11,12],"tldr",{},[13,14,15],"p",{},"Error messages help attackers. Stack traces reveal file paths, database errors expose schema, and verbose errors guide exploitation. Show generic messages to users, log details server-side. These prompts help you implement secure error handling patterns.",[17,18,20],"h2",{"id":19},"error-handler-middleware","Error Handler Middleware",[13,22,23],{},"Use this prompt to set up a centralized Express error handler with a custom AppError class. Your AI will generate environment-aware error middleware that logs full details server-side while returning safe, generic messages to users in production.",[25,26,28,31,34,37,40,43,46],"prompt-box",{"title":27},"Express Error Handler",[13,29,30],{},"Add secure error handling to my Express application.",[13,32,33],{},"// Custom error class\nclass AppError extends Error {\nconstructor(message, statusCode, isOperational = true) {\nsuper(message);\nthis.statusCode = statusCode;\nthis.isOperational = isOperational; // Expected errors vs bugs\nError.captureStackTrace(this, this.constructor);\n}\n}",[13,35,36],{},"// Error handler middleware (must be last)\nconst errorHandler = (err, req, res, next) => {\n// Log full error for debugging\nconsole.error('Error:', {\nmessage: err.message,\nstack: err.stack,\nurl: req.url,\nmethod: req.method,\nuserId: req.user?.id,\ntimestamp: new Date().toISOString()\n});",[13,38,39],{},"// Determine status code\nconst statusCode = err.statusCode || 500;",[13,41,42],{},"// Response based on environment\nif (process.env.NODE_ENV === 'production') {\n// Generic message for production\nres.status(statusCode).json({\nerror: statusCode === 500\n? 'An unexpected error occurred'\n: err.message\n});\n} else {\n// Detailed for development\nres.status(statusCode).json({\nerror: err.message,\nstack: err.stack\n});\n}\n};",[13,44,45],{},"app.use(errorHandler);",[13,47,48],{},"Usage:\nthrow new AppError('Resource not found', 404);\nthrow new AppError('Invalid input', 400);",[17,50,52],{"id":51},"api-error-responses","API Error Responses",[13,54,55],{},"Paste this prompt to create a consistent, secure API error response format. Your AI will generate structured error codes for every HTTP status (400, 401, 403, 404, 429, 500) with safe user-facing messages and request IDs for support correlation.",[25,57,59,62,65,68,71,74,77,80,83,86,89],{"title":58},"Secure API Error Responses",[13,60,61],{},"Make my API error responses secure and consistent.",[13,63,64],{},"// BAD - reveals too much\n{\n\"error\": \"SequelizeDatabaseError: relation \"users\" does not exist\",\n\"query\": \"SELECT * FROM users WHERE id = 1\",\n\"stack\": \"at Query.run (/app/node_modules/sequelize/...\"\n}",[13,66,67],{},"// GOOD - safe for production\n{\n\"error\": {\n\"code\": \"NOT_FOUND\",\n\"message\": \"The requested resource was not found\"\n}\n}",[13,69,70],{},"Error response patterns:",[13,72,73],{},"// 400 Bad Request\n{ \"error\": { \"code\": \"INVALID_INPUT\", \"message\": \"Email format is invalid\" }}",[13,75,76],{},"// 401 Unauthorized\n{ \"error\": { \"code\": \"UNAUTHORIZED\", \"message\": \"Authentication required\" }}",[13,78,79],{},"// 403 Forbidden (don't reveal resource exists)\n{ \"error\": { \"code\": \"NOT_FOUND\", \"message\": \"Resource not found\" }}",[13,81,82],{},"// 404 Not Found\n{ \"error\": { \"code\": \"NOT_FOUND\", \"message\": \"Resource not found\" }}",[13,84,85],{},"// 429 Rate Limited\n{ \"error\": { \"code\": \"RATE_LIMITED\", \"message\": \"Too many requests\" }}",[13,87,88],{},"// 500 Internal Error (never reveal details)\n{ \"error\": { \"code\": \"INTERNAL_ERROR\", \"message\": \"An unexpected error occurred\" }}",[13,90,91],{},"Include request ID for support:\n{ \"error\": { \"code\": \"INTERNAL_ERROR\", \"message\": \"...\", \"requestId\": \"abc123\" }}",[93,94,95],"warning-box",{},[13,96,97,101],{},[98,99,100],"strong",{},"Forbidden vs Not Found:"," Don't tell attackers a resource exists but they can't access it. For sensitive resources, return 404 instead of 403 to avoid revealing existence.",[17,103,105],{"id":104},"database-error-handling","Database Error Handling",[13,107,108],{},"Copy this prompt to generate a database error wrapper that catches ORM exceptions and translates them into safe application errors. Your AI will map common database error codes (unique violations, foreign key failures) to user-friendly messages without exposing table names or queries.",[25,110,112,115,118,134,137,140,151,154,157],{"title":111},"Sanitize Database Errors",[13,113,114],{},"Handle database errors without exposing sensitive details.",[13,116,117],{},"Database errors often contain:",[119,120,121,125,128,131],"ul",{},[122,123,124],"li",{},"Table/column names",[122,126,127],{},"SQL queries",[122,129,130],{},"Connection strings",[122,132,133],{},"Schema information",[13,135,136],{},"Wrap database calls:",[13,138,139],{},"async function safeDbQuery(queryFn) {\ntry {\nreturn await queryFn();\n} catch (error) {\n// Log full error for debugging\nconsole.error('Database error:', {\nmessage: error.message,\ncode: error.code,\nquery: error.sql, // Log but don't expose\nstack: error.stack\n});",[141,142,147],"pre",{"className":143,"code":145,"language":146},[144],"language-text","// Return generic error\nif (error.code === '23505') { // Unique violation\n  throw new AppError('This record already exists', 409);\n}\nif (error.code === '23503') { // Foreign key violation\n  throw new AppError('Referenced record not found', 400);\n}\n\n// Generic for unknown database errors\nthrow new AppError('Database operation failed', 500);\n","text",[148,149,145],"code",{"__ignoreMap":150},"",[13,152,153],{},"}\n}",[13,155,156],{},"// Usage\nconst user = await safeDbQuery(() =>\ndb.users.findUnique({ where: { id } })\n);",[13,158,159],{},"Never pass database error messages directly to responses.",[17,161,163],{"id":162},"frontend-error-handling","Frontend Error Handling",[13,165,166],{},"Use this prompt to create a React Error Boundary component that catches rendering errors gracefully. Your AI will generate a class component with error tracking integration, unique error IDs for support, and a user-friendly fallback UI that never displays stack traces.",[25,168,170,173,176,179,182,188,191,194,200,202,205],{"title":169},"React Error Boundaries",[13,171,172],{},"Add error boundaries that don't leak information in React.",[13,174,175],{},"class ErrorBoundary extends React.Component {\nstate = { hasError: false, errorId: null };",[13,177,178],{},"static getDerivedStateFromError(error) {\nreturn { hasError: true };\n}",[13,180,181],{},"componentDidCatch(error, errorInfo) {\n// Generate unique error ID for support\nconst errorId = crypto.randomUUID();\nthis.setState({ errorId });",[141,183,186],{"className":184,"code":185,"language":146},[144],"// Log to error tracking (Sentry, etc.)\n// Don't show these details to users\nlogError({\n  errorId,\n  error: error.message,\n  stack: error.stack,\n  componentStack: errorInfo.componentStack,\n});\n",[148,187,185],{"__ignoreMap":150},[13,189,190],{},"}",[13,192,193],{},"render() {\nif (this.state.hasError) {\nreturn (",[141,195,198],{"className":196,"code":197,"language":146},[144],"      Something went wrong\n      We've been notified and are working on it.\n      {this.state.errorId && (\n        Error ID: {this.state.errorId}\n      )}\n       window.location.reload()}>\n        Try Again\n\n\n  );\n}\n\nreturn this.props.children;\n",[148,199,197],{"__ignoreMap":150},[13,201,153],{},[13,203,204],{},"// Wrap your app",[13,206,207],{},"Never display error.message or stack traces to users in production.",[209,210,211],"tip-box",{},[13,212,213,216],{},[98,214,215],{},"Pro tip:"," Use error tracking services like Sentry or LogRocket. They capture full error details for debugging while showing users friendly messages. Include request IDs to correlate user reports with logs.",[218,219,220,227],"faq-section",{},[221,222,224],"faq-item",{"question":223},"How do I debug production errors without verbose messages?",[13,225,226],{},"Use error tracking services (Sentry, Bugsnag), structured logging with request IDs, and log aggregation. You get full details in your tools without exposing them to attackers.",[221,228,230],{"question":229},"Should I show different errors for development?",[13,231,232],{},"Yes, but be careful. Check NODE_ENV to show detailed errors only in development. Never deploy with development error handling active.",[17,234,236],{"id":235},"further-reading","Further Reading",[13,238,239],{},"Want to understand the vulnerability before fixing it? These guides explain what's happening and why.",[119,241,242,249,255],{},[122,243,244],{},[245,246,248],"a",{"href":247},"/blog/vulnerabilities/exposed-api-keys","Understanding exposed API keys",[122,250,251],{},[245,252,254],{"href":253},"/blog/how-to/hide-api-keys","How to hide API keys step-by-step",[122,256,257],{},[245,258,260],{"href":259},"/blog/best-practices/secrets","Secret management best practices",[262,263,264,270],"related-articles",{},[265,266],"related-card",{"description":267,"href":268,"title":269},"Log without leaking","/blog/prompts/secure-logging","Secure Logging",[265,271],{"description":272,"href":273,"title":274},"Dev vs production","/blog/prompts/environment-separation","Environment Separation",[276,277,280,284],"cta-box",{"href":278,"label":279},"/","Start Free Scan",[17,281,283],{"id":282},"find-verbose-errors","Find Verbose Errors",[13,285,286],{},"Scan your application for error messages that leak sensitive information.",{"title":150,"searchDepth":288,"depth":288,"links":289},2,[290,291,292,293,294,295],{"id":19,"depth":288,"text":20},{"id":51,"depth":288,"text":52},{"id":104,"depth":288,"text":105},{"id":162,"depth":288,"text":163},{"id":235,"depth":288,"text":236},{"id":282,"depth":288,"text":283},"prompts","2026-02-12","2026-03-06","AI prompts to implement secure error handling. Hide sensitive details from users while logging what you need for debugging.",false,"md",null,"cyan",{},true,"AI prompts to handle errors without leaking sensitive information.","/blog/prompts/add-error-handling","[object Object]","BlogPosting",{"title":5,"description":299},{"loc":307},"blog/prompts/add-error-handling",[314],"Deployment","summary_large_image","SxSFBGd3UhPxnPmepVPZ0Y4fw0-0cXiXEtJ5oryKHYM",1775843939048]