nodejs_error_handling_logging 14 Q&As

Node.js Error Handling Logging FAQ & Answers

14 expert Node.js Error Handling Logging answers researched from official documentation. Every answer cites authoritative sources you can verify.

unknown

14 questions
A

Async errors: always use try-catch with async/await or .catch() with promises. Critical: unhandled promise rejections crash process in Node.js 15+ (default behavior changed from deprecation warning to termination). When --unhandled-rejections flag set to strict or throw (default) and rejection not handled, triggers crash. Best practice: wrap all async operations in try-catch or attach .catch() handlers. Global handler (last resort): process.on('unhandledRejection', err => { log.error(err); process.exit(1); });

99% confidence
A

Event emitter errors: emitter.on('error', handler) for streams, servers prevents uncaught exceptions from event-based I/O. Without error handler, emitter throws exception that can crash process. Critical for streams (fs.createReadStream), HTTP servers (server.on('error')), and any EventEmitter-based code. Always attach error handlers to prevent crashes.

99% confidence
A

Global handlers (last resort only): process.on('uncaughtException', err => { log.error(err); process.exit(1); }) and process.on('unhandledRejection', err => { log.error(err); process.exit(1); }). Official warning: 'uncaughtException' crude mechanism for exception handling, intended only as last resort. Should NOT be used as equivalent to On Error Resume Next. Unhandled exceptions inherently mean application in undefined state - attempting to resume without proper recovery causes additional unforeseen issues. Always log and exit (process may be in inconsistent state).

Sources
99% confidence
A

Express error handling: middleware with 4 params (signature distinguishes from regular middleware): app.use((err, req, res, next) => { log.error(err); res.status(500).json({ error: 'Internal server error' }); }). Never send stack traces to clients in production (security risk, information disclosure). Error middleware must be registered AFTER all routes. Four parameters distinguish error middleware from regular middleware.

Sources
99% confidence
A

Structured logging: use JSON format for parsing (enables log aggregation, querying): log.info({ user_id: 123, action: 'login', ip: '1.2.3.4' }). Log levels: error (bugs requiring immediate attention), warn (potential issues, degraded functionality), info (significant events, startup/shutdown), debug (detailed for development only). Libraries: pino (fastest, 5-10x faster than winston, asynchronous by default), winston (feature-rich, transports), bunyan (structured, deprecated but still used). Performance: pino achieves <1ms per log statement (asynchronous write, worker thread processing).

Sources
99% confidence
A

Contextual logging: correlation IDs across requests for distributed tracing: const logger = log.child({ req_id: uuid() }); creates child logger with request-specific context. AsyncLocalStorage (Node.js async_hooks module, official API) recommended for automatic context propagation across async boundaries. Enables tracking single request through multiple async operations. Critical for debugging distributed systems. Sensitive data: redact passwords, tokens, PII: log.info({ email, password: '[REDACTED]' }). GDPR/compliance requirement for production systems.

Sources
99% confidence
A

Best practices: (1) Log errors with context (user, request, state, stack trace for debugging), (2) Don't log in synchronous hot paths (blocks event loop), use async logging (pino async mode), (3) Rotate logs (logrotate, PM2 handles this automatically), (4) Set log levels via environment (DEBUG in dev, INFO in prod, reduce noise), (5) Monitor error rates (alert on spikes indicating incidents). Centralized logging: ship logs to ELK Stack (Elasticsearch, Logstash, Kibana), Datadog, CloudWatch. Use log aggregation agents (Fluentd, Logstash) or direct HTTP streaming. Valid for Node.js 20+ LTS versions (Node.js 18 EOL 2025).

Sources
99% confidence
A

Async errors: always use try-catch with async/await or .catch() with promises. Critical: unhandled promise rejections crash process in Node.js 15+ (default behavior changed from deprecation warning to termination). When --unhandled-rejections flag set to strict or throw (default) and rejection not handled, triggers crash. Best practice: wrap all async operations in try-catch or attach .catch() handlers. Global handler (last resort): process.on('unhandledRejection', err => { log.error(err); process.exit(1); });

99% confidence
A

Event emitter errors: emitter.on('error', handler) for streams, servers prevents uncaught exceptions from event-based I/O. Without error handler, emitter throws exception that can crash process. Critical for streams (fs.createReadStream), HTTP servers (server.on('error')), and any EventEmitter-based code. Always attach error handlers to prevent crashes.

99% confidence
A

Global handlers (last resort only): process.on('uncaughtException', err => { log.error(err); process.exit(1); }) and process.on('unhandledRejection', err => { log.error(err); process.exit(1); }). Official warning: 'uncaughtException' crude mechanism for exception handling, intended only as last resort. Should NOT be used as equivalent to On Error Resume Next. Unhandled exceptions inherently mean application in undefined state - attempting to resume without proper recovery causes additional unforeseen issues. Always log and exit (process may be in inconsistent state).

Sources
99% confidence
A

Express error handling: middleware with 4 params (signature distinguishes from regular middleware): app.use((err, req, res, next) => { log.error(err); res.status(500).json({ error: 'Internal server error' }); }). Never send stack traces to clients in production (security risk, information disclosure). Error middleware must be registered AFTER all routes. Four parameters distinguish error middleware from regular middleware.

Sources
99% confidence
A

Structured logging: use JSON format for parsing (enables log aggregation, querying): log.info({ user_id: 123, action: 'login', ip: '1.2.3.4' }). Log levels: error (bugs requiring immediate attention), warn (potential issues, degraded functionality), info (significant events, startup/shutdown), debug (detailed for development only). Libraries: pino (fastest, 5-10x faster than winston, asynchronous by default), winston (feature-rich, transports), bunyan (structured, deprecated but still used). Performance: pino achieves <1ms per log statement (asynchronous write, worker thread processing).

Sources
99% confidence
A

Contextual logging: correlation IDs across requests for distributed tracing: const logger = log.child({ req_id: uuid() }); creates child logger with request-specific context. AsyncLocalStorage (Node.js async_hooks module, official API) recommended for automatic context propagation across async boundaries. Enables tracking single request through multiple async operations. Critical for debugging distributed systems. Sensitive data: redact passwords, tokens, PII: log.info({ email, password: '[REDACTED]' }). GDPR/compliance requirement for production systems.

Sources
99% confidence
A

Best practices: (1) Log errors with context (user, request, state, stack trace for debugging), (2) Don't log in synchronous hot paths (blocks event loop), use async logging (pino async mode), (3) Rotate logs (logrotate, PM2 handles this automatically), (4) Set log levels via environment (DEBUG in dev, INFO in prod, reduce noise), (5) Monitor error rates (alert on spikes indicating incidents). Centralized logging: ship logs to ELK Stack (Elasticsearch, Logstash, Kibana), Datadog, CloudWatch. Use log aggregation agents (Fluentd, Logstash) or direct HTTP streaming. Valid for Node.js 20+ LTS versions (Node.js 18 EOL 2025).

Sources
99% confidence