npm package: @onlineapps/conn-infra-error-handler
Description: Unified error handling with retry strategies, circuit breaker, and compensation patterns
Author: OA Drive Team
Latest version: 1.0.9

# @onlineapps/conn-infra-error-handler

## Overview
Error handling connector for business services. Wraps `@onlineapps/error-handler-core` and integrates with `@onlineapps/conn-base-monitoring` for unified error handling and logging.

**Note:** This connector is for business services using ServiceWrapper. Infrastructure services should use `@onlineapps/error-handler-core` directly.

## Installation
```bash
npm install @onlineapps/conn-infra-error-handler
```

## Features
- **Error Classification** - Automatic error type detection (TRANSIENT, BUSINESS, FATAL, etc.)
- **Retry Logic** - Exponential backoff for transient errors
- **Circuit Breaker** - Protection against cascading failures
- **DLQ Routing** - Dead letter queue routing for permanent errors
- **Compensation** - Rollback operations for failed workflows
- **Unified Logging** - Structured error logging via monitoring-core

## Architecture

This connector wraps `@onlineapps/error-handler-core` and integrates with `@onlineapps/conn-base-monitoring`:

```
conn-infra-error-handler (wrapper)
  └─> error-handler-core (core logic)
       └─> monitoring-core (logging)
```

See [Unified Error Handling Standard](/docs/standards/UNIFIED_ERROR_HANDLING.md) for complete architecture details.

## Usage

### Basic Setup (via ServiceWrapper)

The error handler is automatically integrated when using ServiceWrapper:

```javascript
const { ServiceWrapper } = require('@onlineapps/service-wrapper');

const wrapper = new ServiceWrapper({
  serviceName: 'my-service',
  monitoring: { enabled: true },
  errorHandling: {
    maxRetries: 3,
    retryDelay: 1000
  }
});

// Error handler is available as wrapper.errorHandler
```

### Direct Usage

```javascript
const { ErrorHandlerConnector } = require('@onlineapps/conn-infra-error-handler');
const { init: initMonitoring } = require('@onlineapps/conn-base-monitoring');

// Initialize monitoring first
const monitoring = await initMonitoring({
  serviceName: 'my-service',
  mode: 'light'
});

// Initialize error handler
const errorHandler = new ErrorHandlerConnector({
  serviceName: 'my-service',
  serviceVersion: '1.0.0',
  environment: 'production',
  monitoring: monitoring,  // Required: conn-base-monitoring instance
  handling: {
    maxRetries: 3,
    retryDelay: 1000,
    retryMultiplier: 2,
    circuitBreakerEnabled: true,
    dlqEnabled: true,
    mqClient: mqClient  // Optional, for DLQ routing
  }
});
```

### Error Classification
```javascript
try {
  await processMessage(message);
} catch (error) {
  const classified = errorHandler.classify(error);

  if (classified.isTransient) {
    // Retry-able error (network, timeout)
    await errorHandler.handleTransient(error, message);
  } else {
    // Permanent error (validation, business logic)
    await errorHandler.handlePermanent(error, message);
  }
}
```

### Retry Logic
```javascript
const result = await errorHandler.withRetry(async () => {
  return await externalService.call();
}, {
  maxAttempts: 3,
  backoffMultiplier: 2,
  initialDelay: 100
});
```

## Configuration

### Options
```javascript
{
  serviceName: 'service-name',     // Required
  maxRetries: 3,                    // Default: 3
  retryDelay: 1000,                 // Default: 1000ms
  enableDLQ: true,                  // Default: true
  dlqName: 'workflow.error',        // Default: workflow.error
  logLevel: 'error',                // Default: error
  includeStackTrace: true           // Default: true in dev
}
```

### Environment Variables
```bash
ERROR_MAX_RETRIES=3
ERROR_RETRY_DELAY=1000
ERROR_DLQ_ENABLED=true
ERROR_DLQ_NAME=workflow.error
```

## Error Types

### Transient Errors
Automatically retried:
- Network errors (ECONNREFUSED, ETIMEDOUT)
- Service unavailable (503)
- Rate limiting (429)
- Temporary database issues

### Permanent Errors
Sent to DLQ immediately:
- Validation errors (400)
- Authentication errors (401)
- Not found errors (404)
- Business logic errors

## API Reference

### ErrorHandler

#### initialize()
Initializes the error handler with configured options.

#### classify(error)
Classifies an error as transient or permanent.
Returns: `{ isTransient: boolean, category: string, retryable: boolean }`

#### handleTransient(error, context)
Handles transient errors with retry logic.

#### handlePermanent(error, context)
Routes permanent errors to DLQ.

#### withRetry(fn, options)
Wraps a function with retry logic.

#### enrichError(error, context)
Adds context information to error object.

## Error Context
```javascript
{
  workflowId: 'wf-uuid',
  spanId: 'span-uuid',
  service: 'hello-service',
  operation: 'greet',
  timestamp: 'ISO-8601',
  retryCount: 2,
  maxRetries: 3,
  errorCode: 'NETWORK_ERROR',
  errorMessage: 'Connection refused',
  stackTrace: '...'
}
```

## Integration with Service Wrapper

The error handler is automatically integrated when using service-wrapper:

```javascript
const { ServiceWrapper } = require('@onlineapps/service-wrapper');

const wrapper = new ServiceWrapper({
  errorHandling: {
    enabled: true,
    maxRetries: 3
  }
});

// Error handling is automatically configured
```

## Testing

```bash
npm test                 # Run all tests
npm run test:unit        # Unit tests only
npm run test:component   # Component tests
```

## Dependencies
- `@onlineapps/error-handler-core` - Core error handling functionality
- `@onlineapps/conn-base-monitoring` - Monitoring integration for business services

## Related Documentation
- [Unified Error Handling Standard](/docs/standards/UNIFIED_ERROR_HANDLING.md) - Complete error handling architecture
- [Error Handling Architecture](/docs/standards/ERROR_HANDLING_ARCHITECTURE.md) - Core vs connector distinction
- [Error Handling Standard](/docs/standards/ERROR_HANDLING.md) - Fail loudly principle
- [Service Wrapper](/shared/connector/service-wrapper/README.md) - Integration guide

---
*Version: 1.0.0 | License: MIT*