P
💻DeveloppementIntermediateClaude

Implement Robust Error Handling in Node.js

Create a professional Node.js error handling architecture with custom error classes, centralized middleware, and monitoring.

Paste in your AI

Paste this prompt in ChatGPT, Claude or Gemini and customize the variables in brackets.

Tu es un expert Node.js spécialisé dans la création d'applications robustes et résilientes. Je dois implémenter une gestion des erreurs professionnelle dans mon application.

Contexte de l'application :

  • Framework : [EX: Express 4, Fastify, Koa, NestJS]
  • Type d'application : [EX: API REST, application web fullstack, microservice]
  • Sources d'erreurs : [EX: base de données PostgreSQL, APIs tierces Stripe/Sendgrid, système de fichiers]
  • Logging actuel : [EX: console.log, Winston, Pino]
  • Monitoring : [EX: Sentry, Datadog, aucun]

Problèmes actuels :
[DÉCRIRE_LES_PROBLÈMES: ex. erreurs non capturées qui crashent l'app, pas de distinction erreur métier/technique, logs insuffisants]

Implémente une stratégie de gestion des erreurs complète :

  1. Hiérarchie de classes d'erreurs : crée une classe AppError de base et des classes spécialisées (ValidationError, NotFoundError, UnauthorizedError, DatabaseError, ExternalServiceError) avec codes d'erreur standardisés.
  2. Middleware de gestion des erreurs : middleware Express centralisé qui normalise toutes les erreurs, formate les réponses JSON et gère différemment les erreurs opérationnelles et les bugs.
  3. Capture des erreurs non gérées : gestion des process.on('uncaughtException') et process.on('unhandledRejection') avec graceful shutdown.
  4. Logging structuré : format JSON avec correlation ID, stack trace en développement uniquement, séparation des niveaux de log.
  5. Intégration monitoring : configuration Sentry ou équivalent avec contexte utilisateur et release tracking.
  6. Tests : tests unitaires pour la hiérarchie d'erreurs et le middleware.
100% found this useful

Personalize this prompt with Léa

Léa rewrites this prompt for your job and your exact goal — 3 quick questions.

Why this prompt works

<p>This prompt intelligently distinguishes operational errors (predictable, manageable: user not found, validation failed) from programming errors (unexpected bugs: undefined is not a function). This distinction is fundamental for deciding the recovery strategy: retry for the former, alert and restart for the latter.</p><p>Creating an error class hierarchy with standardized codes is a professional development practice that allows API clients to handle errors programmatically rather than parsing text messages. This is the foundation of a robust API.</p><p>Including uncaughtException and unhandledRejection handling with graceful shutdown is often missed by junior Node.js developers, but it is critical in production to avoid corrupted states and ensure in-flight requests complete properly.</p>

Use Cases

Improving Node.js API robustnessSetting up error monitoringStandardizing error handling across a team

Expected Output

Error class hierarchy, Express middleware, uncaught error handling, logging configuration, and monitoring integration.

Improve this prompt

Run this prompt through the Optimizer to strengthen its context, constraints and expected format.

Improve this prompt with the Optimizer

Comments

  • LéaAI

    Ajoutez un champ `statusCode` à vos classes d'erreurs pour les mapper directement au middleware HTTP. Pour éviter les `unhandledRejection`, utilisez un pattern `Result` (soit `Ok`, soit `Err`) dans les appels aux services externes : cela rend les erreurs explicites et permet un retour structuré vers le middleware centralisé.

📬 Get new prompts every week

Join our newsletter and never miss a prompt.

Go further

Similar Prompts

💻DeveloppementBeginnerAll AIs

Brand Comment Responses

Consistent and fast social media community management

0219
💻DeveloppementIntermediateClaude

Complete Code Review for Pull Requests

Get an exhaustive code review covering quality, performance, security, and maintainability for any language.

34561
💻DeveloppementAdvancedChatGPT

Master Advanced TypeScript Types

Strengthen your code's type safety with advanced generics, utility types, and discriminated unions.

39549
💻DeveloppementIntermediateAll AIs

Perplexity Prompt for Generating Python Code

Perplexity AI stands out from other AI assistants with its unique ability to combine real-time web search and code generation. When it comes to producing Python code, this advantage is significant: Perplexity can rely on the latest official documentation, current best practices, and up-to-date libraries to generate reliable and modern code. Unlike a classic LLM whose knowledge is frozen at a cutoff date, Perplexity verifies its sources in real time, drastically reducing the risk of obsolete code or deprecated functions. Whether you are a developer looking to speed up your workflow, a data scientist wanting to prototype quickly, or a beginner learning Python, a well-structured prompt turns Perplexity into a true development assistant. The key lies in the precision of your request: by specifying the technical context, constraints, and expected output format, you get production-ready code rather than a generic snippet. This guide offers optimized prompts to get the most out of Perplexity in your Python projects.

0204