CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-n8n-workflow

Workflow base code of n8n providing foundational workflow execution engine for automation platform

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

error-handling.mddocs/

Error Handling

Structured error handling with specific error classes for different failure scenarios, including node errors, workflow errors, expression errors, and comprehensive error reporting capabilities.

Capabilities

Base Error Classes

Foundation error classes providing common error handling functionality.

/**
 * Base class for all execution-related errors
 */
abstract class ExecutionBaseError extends Error {
  name: string;
  message: string;
  cause?: Error;
  context?: IDataObject;
  timestamp: Date;

  constructor(message: string, options?: ErrorOptions);
  
  /**
   * Get error details for logging
   * @returns Error details object
   */
  getErrorDetails(): IErrorDetails;
}

/**
 * Base class for node-related errors
 */
abstract class NodeError extends ExecutionBaseError {
  node: INode;
  itemIndex?: number;
  runIndex?: number;

  constructor(node: INode, message: string, options?: NodeErrorOptions);
}

/**
 * Base class for workflow-related errors
 */
abstract class WorkflowError extends ExecutionBaseError {
  workflow?: Workflow;
  
  constructor(message: string, options?: WorkflowErrorOptions);
}

interface ErrorOptions {
  cause?: Error;
  context?: IDataObject;
}

interface NodeErrorOptions extends ErrorOptions {
  itemIndex?: number;
  runIndex?: number;
}

interface WorkflowErrorOptions extends ErrorOptions {
  workflow?: Workflow;
}

Node Operation Errors

Specific error classes for node execution failures and API errors.

/**
 * Error for node operation failures
 */
class NodeOperationError extends NodeError {
  functionality: string;
  
  constructor(
    node: INode, 
    message: string, 
    options?: NodeOperationErrorOptions
  );

  /**
   * Create error with recommendation
   * @param node - Node that failed
   * @param message - Error message
   * @param functionality - Failed functionality description
   * @returns Node operation error with recommendation
   */
  static createWithRecommendation(
    node: INode,
    message: string,
    functionality: string
  ): NodeOperationError;
}

/**
 * Error for API-related node failures
 */
class NodeApiError extends NodeError {
  httpCode?: number;
  responseData?: any;
  
  constructor(
    node: INode,
    httpRequestOptions: IHttpRequestOptions,
    response?: any,
    options?: NodeApiErrorOptions
  );

  /**
   * Get HTTP status code
   * @returns HTTP status code or undefined
   */
  getHttpCode(): number | undefined;

  /**
   * Get response data
   * @returns API response data
   */
  getResponseData(): any;
}

/**
 * Error for SSL/TLS related issues
 */
class NodeSSLError extends NodeError {
  constructor(node: INode, cause: Error);
}

interface NodeOperationErrorOptions extends NodeErrorOptions {
  functionality?: string;
  recommendation?: string;
}

interface NodeApiErrorOptions extends NodeErrorOptions {
  httpCode?: number;
  responseData?: any;
}

Workflow Errors

Error classes for workflow-level failures and operations.

/**
 * Error for workflow activation failures
 */
class WorkflowActivationError extends WorkflowError {
  constructor(message: string, workflow: Workflow, cause?: Error);
}

/**
 * Error for general workflow operation failures
 */
class WorkflowOperationError extends WorkflowError {
  constructor(message: string, options?: WorkflowErrorOptions);
}

/**
 * Error for workflow execution cancellation
 */
class ExecutionCancelledError extends WorkflowError {
  constructor(message?: string);
}

Expression Errors

Specialized errors for expression evaluation failures.

/**
 * Error for expression evaluation failures
 */
class ExpressionError extends Error {
  description: string;
  cause?: Error;
  context?: IExpressionErrorContext;

  constructor(
    message: string, 
    options?: ExpressionErrorOptions
  );

  /**
   * Get expression context information
   * @returns Expression error context
   */
  getContext(): IExpressionErrorContext | undefined;
}

interface IExpressionErrorContext {
  expression: string;
  itemIndex?: number;
  runIndex?: number;
  parameter?: string;
  nodeName?: string;
}

interface ExpressionErrorOptions {
  cause?: Error;
  context?: IExpressionErrorContext;
  description?: string;
}

Error Reporter and Utilities

Error reporting and utility functions for error handling.

/**
 * Error reporter proxy for centralized error handling
 */
class ErrorReporterProxy {
  /**
   * Report error with context
   * @param error - Error to report
   * @param context - Additional context
   */
  static report(error: Error, context?: IErrorContext): void;

  /**
   * Create error report
   * @param error - Error to create report for
   * @returns Error report object
   */
  static createReport(error: Error): IErrorReport;
}

interface IErrorContext {
  workflowId?: string;
  executionId?: string;
  nodeId?: string;
  userId?: string;
  additional?: IDataObject;
}

interface IErrorReport {
  message: string;
  stack?: string;
  type: string;
  context?: IErrorContext;
  timestamp: Date;
  level: 'error' | 'warning' | 'info';
}

/**
 * Application-level error class
 */
class ApplicationError extends Error {
  level: 'error' | 'warning' | 'info';
  
  constructor(
    message: string, 
    options?: ApplicationErrorOptions
  );
}

interface ApplicationErrorOptions {
  level?: 'error' | 'warning' | 'info';
  cause?: Error;
  tags?: string[];
}

Error Analysis and Recovery

Functions for error analysis, categorization, and recovery suggestions.

/**
 * Analyze error and categorize
 * @param error - Error to analyze
 * @returns Error analysis result
 */
function analyzeError(error: Error): IErrorAnalysis;

/**
 * Get error recovery suggestions
 * @param error - Error to analyze
 * @returns Array of recovery suggestions
 */
function getRecoverySuggestions(error: Error): IRecoverySuggestion[];

/**
 * Check if error is retryable
 * @param error - Error to check
 * @returns Boolean indicating if error is retryable
 */
function isRetryableError(error: Error): boolean;

interface IErrorAnalysis {
  category: 'network' | 'authentication' | 'validation' | 'configuration' | 'system' | 'unknown';
  severity: 'low' | 'medium' | 'high' | 'critical';
  isRetryable: boolean;
  cause?: string;
  affectedComponents: string[];
}

interface IRecoverySuggestion {
  action: string;
  description: string;
  priority: 'high' | 'medium' | 'low';
  automatic?: boolean;
}

/**
 * Wrap function with error handling
 * @param fn - Function to wrap
 * @param errorHandler - Error handler function
 * @returns Wrapped function with error handling
 */
function withErrorHandling<T extends (...args: any[]) => any>(
  fn: T,
  errorHandler: (error: Error) => void
): T;

Error Formatting and Logging

Utilities for error formatting, serialization, and logging.

/**
 * Format error for display
 * @param error - Error to format
 * @param includeStack - Include stack trace
 * @returns Formatted error string
 */
function formatError(error: Error, includeStack?: boolean): string;

/**
 * Serialize error for storage/transmission
 * @param error - Error to serialize
 * @returns Serialized error object
 */
function serializeError(error: Error): ISerializedError;

/**
 * Deserialize error from storage
 * @param serializedError - Serialized error data
 * @returns Reconstructed error object
 */
function deserializeError(serializedError: ISerializedError): Error;

interface ISerializedError {
  name: string;
  message: string;
  stack?: string;
  cause?: ISerializedError;
  context?: IDataObject;
  timestamp?: string;
  [key: string]: any;
}

/**
 * Create error with additional context
 * @param originalError - Original error
 * @param additionalContext - Additional context to add
 * @returns Enhanced error with context
 */
function enhanceError(
  originalError: Error,
  additionalContext: IDataObject
): Error;

Usage Examples:

import { 
  NodeOperationError,
  NodeApiError,
  ExpressionError,
  WorkflowOperationError,
  ErrorReporterProxy,
  analyzeError,
  withErrorHandling
} from "n8n-workflow";

// Node operation error
try {
  // Node operation that might fail
  const result = await performNodeOperation();
} catch (error) {
  throw new NodeOperationError(
    currentNode,
    'Failed to process data: Invalid format',
    {
      functionality: 'Data Processing',
      itemIndex: currentItemIndex,
      cause: error
    }
  );
}

// API error handling
try {
  const response = await this.helpers.httpRequest(requestOptions);
} catch (error) {
  if (error.response) {
    throw new NodeApiError(
      currentNode,
      requestOptions,
      error.response,
      {
        httpCode: error.response.status,
        responseData: error.response.data
      }
    );
  } else {
    throw new NodeOperationError(
      currentNode,
      `Network request failed: ${error.message}`
    );
  }
}

// Expression error
try {
  const result = expression.resolveSimpleParameterValue(
    "{{ $json.invalidProperty.nonExistent }}",
    {},
    'string'
  );
} catch (error) {
  throw new ExpressionError(
    'Cannot access property of undefined',
    {
      cause: error,
      context: {
        expression: "{{ $json.invalidProperty.nonExistent }}",
        itemIndex: 0,
        nodeName: 'Data Transform'
      }
    }
  );
}

// Workflow error
try {
  await workflow.execute('manual');
} catch (error) {
  throw new WorkflowOperationError(
    'Workflow execution failed due to invalid configuration',
    {
      workflow,
      cause: error
    }
  );
}

// Error reporting
try {
  await riskOperation();
} catch (error) {
  ErrorReporterProxy.report(error, {
    workflowId: 'workflow-123',
    executionId: 'exec-456',
    nodeId: 'node-789',
    additional: { 
      operation: 'data-sync',
      timestamp: new Date().toISOString()
    }
  });
  throw error;
}

// Error analysis and recovery
try {
  await unreliableOperation();
} catch (error) {
  const analysis = analyzeError(error);
  
  console.log(`Error category: ${analysis.category}`);
  console.log(`Severity: ${analysis.severity}`);
  console.log(`Retryable: ${analysis.isRetryable}`);
  
  if (analysis.isRetryable) {
    const suggestions = getRecoverySuggestions(error);
    suggestions.forEach(suggestion => {
      console.log(`Recovery: ${suggestion.action} - ${suggestion.description}`);
    });
  }
}

// Function wrapping with error handling
const safeDatabaseOperation = withErrorHandling(
  async (data: any) => {
    return await database.save(data);
  },
  (error: Error) => {
    console.error('Database operation failed:', error.message);
    ErrorReporterProxy.report(error, { operation: 'database-save' });
  }
);

// Usage with continue on fail
export async function execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
  const items = this.getInputData();
  const returnData: INodeExecutionData[] = [];

  for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
    try {
      const result = await processItem(items[itemIndex]);
      returnData.push({ json: result });
    } catch (error) {
      if (this.continueOnFail()) {
        returnData.push({
          json: { error: error.message },
          error: error instanceof NodeError ? error : new NodeOperationError(
            this.getNode(),
            error.message,
            { itemIndex, cause: error }
          )
        });
      } else {
        throw error;
      }
    }
  }

  return [returnData];
}

docs

constants.md

data-proxy.md

error-handling.md

expression-system.md

extension-system.md

graph-utilities.md

index.md

node-execution.md

specialized-modules.md

type-guards.md

type-validation.md

utilities.md

workflow-management.md

tile.json