CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-winston

A comprehensive, multi-transport logging library for Node.js applications providing flexible and extensible logging capabilities.

Pending
Overview
Eval results
Files

exception-rejection-handling.mddocs/

Exception and Rejection Handling

Automatic handling of uncaught exceptions and unhandled promise rejections with configurable transports and exit behavior.

Capabilities

Exception Handler

Class for handling uncaught exceptions in Node.js applications with configurable logging transports.

/**
 * Handler for uncaught exceptions
 */
class ExceptionHandler {
  constructor(logger: Logger);
  
  /** Associated logger instance */
  logger: Logger;
  /** Map of registered transport handlers */
  handlers: Map<any, any>;
  /** Exception catcher function or boolean flag */
  catcher: Function | boolean;
}

Exception Handling Methods

Methods for configuring and managing exception handling behavior.

/**
 * Add transports to handle uncaught exceptions
 * @param transports - Transport instances or arrays of transports
 */
handle(...transports: Transport[]): void;

/**
 * Remove transports from exception handling
 * @param transports - Transport instances or arrays of transports
 */
unhandle(...transports: Transport[]): void;

/**
 * Get comprehensive information about an exception
 * @param err - Error string or Error object
 * @returns Object containing error details
 */
getAllInfo(err: string | Error): object;

/**
 * Get current process information
 * @returns Object containing process details
 */
getProcessInfo(): object;

/**
 * Get operating system information
 * @returns Object containing OS details
 */
getOsInfo(): object;

/**
 * Get stack trace information from error
 * @param err - Error object
 * @returns Object containing stack trace details
 */
getTrace(err: Error): object;

Usage Examples:

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ]
});

// Handle exceptions with specific transports
logger.exceptions.handle(
  new winston.transports.File({ filename: 'exceptions.log' }),
  new winston.transports.Console({
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.errors({ stack: true }),
      winston.format.json()
    )
  })
);

// Remove exception handling
logger.exceptions.unhandle(
  new winston.transports.Console()
);

// Custom exception information
process.on('uncaughtException', (err) => {
  const info = logger.exceptions.getAllInfo(err);
  console.log('Exception details:', info);
});

Rejection Handler

Class for handling unhandled promise rejections with configurable logging transports.

/**
 * Handler for unhandled promise rejections
 */
class RejectionHandler {
  constructor(logger: Logger);
  
  /** Associated logger instance */
  logger: Logger;
  /** Map of registered transport handlers */
  handlers: Map<any, any>;
  /** Rejection catcher function or boolean flag */
  catcher: Function | boolean;
}

Rejection Handling Methods

Methods for configuring and managing promise rejection handling behavior.

/**
 * Add transports to handle unhandled promise rejections
 * @param transports - Transport instances or arrays of transports
 */
handle(...transports: Transport[]): void;

/**
 * Remove transports from rejection handling
 * @param transports - Transport instances or arrays of transports
 */
unhandle(...transports: Transport[]): void;

/**
 * Get comprehensive information about a rejection
 * @param err - Error string or Error object
 * @returns Object containing rejection details
 */
getAllInfo(err: string | Error): object;

/**
 * Get current process information
 * @returns Object containing process details
 */
getProcessInfo(): object;

/**
 * Get operating system information
 * @returns Object containing OS details
 */
getOsInfo(): object;

/**
 * Get stack trace information from error
 * @param err - Error object
 * @returns Object containing stack trace details
 */
getTrace(err: Error): object;

Usage Examples:

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ]
});

// Handle promise rejections
logger.rejections.handle(
  new winston.transports.File({ filename: 'rejections.log' }),
  new winston.transports.Console({
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.errors({ stack: true }),
      winston.format.json()
    )
  })
);

// Remove rejection handling
logger.rejections.unhandle(
  new winston.transports.File({ filename: 'rejections.log' })
);

Global Exception and Rejection Handling

Methods available on the winston module for handling exceptions and rejections with the default logger.

/**
 * Handle uncaught exceptions with default logger
 * @param transports - Transport instances for exception logging
 */
function handleExceptions(...transports: Transport[]): void;

/**
 * Stop handling uncaught exceptions with default logger
 * @param transports - Transport instances to remove
 */
function unhandleExceptions(...transports: Transport[]): void;

/**
 * Handle unhandled promise rejections with default logger
 * @param transports - Transport instances for rejection logging
 */
function handleRejections(...transports: Transport[]): void;

/**
 * Stop handling unhandled promise rejections with default logger
 * @param transports - Transport instances to remove
 */
function unhandleRejections(...transports: Transport[]): void;

Usage Examples:

const winston = require('winston');

// Configure default logger first
winston.add(new winston.transports.Console());

// Handle exceptions globally
winston.handleExceptions(
  new winston.transports.File({ filename: 'exceptions.log' })
);

// Handle rejections globally
winston.handleRejections(
  new winston.transports.File({ filename: 'rejections.log' })
);

// Stop handling
winston.unhandleExceptions();
winston.unhandleRejections();

Logger Configuration with Exception Handling

Configure exception and rejection handling during logger creation.

interface LoggerOptions {
  /** Automatically handle uncaught exceptions */
  handleExceptions?: boolean;
  /** Automatically handle unhandled promise rejections */
  handleRejections?: boolean;
  /** Specific transports for exception handling */
  exceptionHandlers?: Transport[];
  /** Specific transports for rejection handling */
  rejectionHandlers?: Transport[];
}

Usage Examples:

const winston = require('winston');

// Logger with built-in exception/rejection handling
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ],
  handleExceptions: true,
  handleRejections: true,
  exceptionHandlers: [
    new winston.transports.File({ filename: 'exceptions.log' })
  ],
  rejectionHandlers: [
    new winston.transports.File({ filename: 'rejections.log' })
  ]
});

// Exit behavior configuration
logger.exitOnError = false; // Don't exit on handled exceptions

Advanced Exception Handling Patterns

Custom exception processing:

const winston = require('winston');

class CustomExceptionHandler {
  constructor() {
    this.logger = winston.createLogger({
      transports: [
        new winston.transports.File({ filename: 'app.log' })
      ]
    });

    // Custom exception handling
    this.logger.exceptions.handle(
      new winston.transports.File({ 
        filename: 'exceptions.log',
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.printf(({ timestamp, level, message, stack }) => {
            return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack}`;
          })
        )
      })
    );

    // Custom rejection handling
    this.logger.rejections.handle(
      new winston.transports.File({ 
        filename: 'rejections.log',
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.json()
        )
      })
    );
  }

  setupGlobalHandlers() {
    // Additional custom handling
    process.on('uncaughtException', (err) => {
      const info = this.logger.exceptions.getAllInfo(err);
      console.error('Uncaught Exception:', info);
      
      // Custom notification logic
      this.notifyAdministrators(err);
      
      // Graceful shutdown
      setTimeout(() => process.exit(1), 1000);
    });

    process.on('unhandledRejection', (reason, promise) => {
      const info = this.logger.rejections.getAllInfo(reason);
      console.error('Unhandled Rejection at:', promise, 'reason:', info);
      
      // Custom handling logic
      this.handleRejection(reason, promise);
    });
  }

  notifyAdministrators(error) {
    // Implementation for admin notification
    console.log('Notifying administrators of error:', error.message);
  }

  handleRejection(reason, promise) {
    // Implementation for custom rejection handling
    console.log('Handling rejection:', reason);
  }
}

const exceptionHandler = new CustomExceptionHandler();
exceptionHandler.setupGlobalHandlers();

Production-ready exception handling:

const winston = require('winston');

const createProductionLogger = () => {
  return winston.createLogger({
    level: 'info',
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.errors({ stack: true }),
      winston.format.json()
    ),
    transports: [
      new winston.transports.File({ 
        filename: 'app.log',
        maxsize: 5242880, // 5MB
        maxFiles: 10
      })
    ],
    handleExceptions: true,
    handleRejections: true,
    exceptionHandlers: [
      new winston.transports.File({ 
        filename: 'exceptions.log',
        maxsize: 5242880,
        maxFiles: 5
      })
    ],
    rejectionHandlers: [
      new winston.transports.File({ 
        filename: 'rejections.log',
        maxsize: 5242880,
        maxFiles: 5
      })
    ],
    exitOnError: false
  });
};

const logger = createProductionLogger();

// Graceful shutdown handling
process.on('SIGTERM', () => {
  logger.info('SIGTERM received, shutting down gracefully');
  logger.close();
  process.exit(0);
});

process.on('SIGINT', () => {
  logger.info('SIGINT received, shutting down gracefully');
  logger.close();
  process.exit(0);
});

Install with Tessl CLI

npx tessl i tessl/npm-winston

docs

container-management.md

default-logger.md

exception-rejection-handling.md

formats.md

index.md

logger-management.md

profiling.md

transports.md

tile.json