# Error Handling Module Structure

```
erp-suite/apps/shared-libs/core/errors/
│
├── Core Implementation Files
│   ├── base-error.ts                    # Base error class & ErrorResponse interface
│   ├── http-errors.ts                   # 7 HTTP-specific error classes
│   ├── error-filter.ts                  # NestJS GlobalExceptionFilter
│   ├── error-middleware.ts              # Express error middleware
│   └── index.ts                         # Module exports
│
├── Documentation
│   ├── README.md                        # Comprehensive documentation (13 KB)
│   ├── INTEGRATION_GUIDE.md             # Step-by-step integration guide (9.4 KB)
│   ├── IMPLEMENTATION_SUMMARY.md        # Implementation summary (7.2 KB)
│   ├── QUICK_REFERENCE.md              # Quick reference cheat sheet (4.9 KB)
│   └── STRUCTURE.md                     # This file
│
└── Examples
    ├── nestjs-integration.example.ts    # Complete NestJS example (6.7 KB)
    └── express-integration.example.ts   # Complete Express example (12 KB)
```

## File Purposes

### Core Files

**base-error.ts**
- `ErrorResponse` interface: Standardized error response structure
- `BaseError` abstract class: Base for all custom errors
- Methods: `toResponse()` for HTTP response conversion

**http-errors.ts**
- BadRequestError (400)
- UnauthorizedError (401)
- ForbiddenError (403)
- NotFoundError (404)
- ConflictError (409)
- ValidationError (422)
- InternalServerError (500)

**error-filter.ts**
- `GlobalExceptionFilter`: NestJS exception filter
- Handles: BaseError, HttpException, generic errors
- Features: Request ID tracking, severity-based logging

**error-middleware.ts**
- `createErrorMiddleware()`: Factory function
- `errorMiddleware`: Default instance
- `notFoundMiddleware`: 404 handler
- `ErrorLogger` interface
- `ErrorMiddlewareOptions` interface

**index.ts**
- Barrel exports for all error handling components

### Documentation Files

**README.md** - Main documentation
- Overview and installation
- Quick start guides
- Detailed API reference
- Best practices
- Migration guide
- Testing examples

**INTEGRATION_GUIDE.md** - Integration instructions
- Step-by-step for each backend
- NestJS integration
- Express integration
- Common patterns
- Migration checklist

**IMPLEMENTATION_SUMMARY.md** - Summary
- Files created
- Features implemented
- Integration requirements
- Benefits
- Next steps

**QUICK_REFERENCE.md** - Cheat sheet
- Quick imports
- Error class reference
- Common patterns
- Setup snippets
- DOs and DON'Ts

**STRUCTURE.md** - This file
- Module structure
- File purposes
- Dependencies

### Example Files

**nestjs-integration.example.ts**
- Bootstrap configuration
- Global filter setup
- Service examples
- Controller examples
- Request ID middleware
- Custom domain errors

**express-integration.example.ts**
- App setup
- Middleware configuration
- Router examples
- Async handler wrapper
- Custom logger integration
- Service layer examples

## Dependencies

### External Dependencies
- `@nestjs/common` (for NestJS filter)
- `express` (for Express middleware)
- `crypto` (for request ID generation)

### Internal Dependencies
- None (standalone module in @erp-suite/core)

## Exports

All exports available from `@erp-suite/core`:

```typescript
// Types
import { ErrorResponse } from '@erp-suite/core';

// Base class
import { BaseError } from '@erp-suite/core';

// HTTP errors
import {
  BadRequestError,
  UnauthorizedError,
  ForbiddenError,
  NotFoundError,
  ConflictError,
  ValidationError,
  InternalServerError,
} from '@erp-suite/core';

// NestJS
import { GlobalExceptionFilter } from '@erp-suite/core';

// Express
import {
  createErrorMiddleware,
  errorMiddleware,
  notFoundMiddleware,
  ErrorLogger,
  ErrorMiddlewareOptions,
} from '@erp-suite/core';
```

## Target Backends

1. **gamilit** - NestJS backend
   - Location: `~/workspace/projects/gamilit/apps/backend`
   - Integration: GlobalExceptionFilter

2. **trading-platform** - Express backend
   - Location: `~/workspace/projects/trading-platform/apps/backend`
   - Integration: createErrorMiddleware

3. **platform_marketing_content** - NestJS backend
   - Location: `~/workspace/projects/platform_marketing_content/apps/backend`
   - Integration: GlobalExceptionFilter

## Integration Flow

```
1. Import from @erp-suite/core
   ↓
2. Setup (one-time)
   - NestJS: Register GlobalExceptionFilter
   - Express: Add error middleware
   ↓
3. Usage (in services/controllers)
   - Throw standardized error classes
   - No try/catch in controllers/routes
   ↓
4. Automatic handling
   - Filter/middleware catches errors
   - Converts to ErrorResponse format
   - Logs with appropriate severity
   - Returns to client
```

## Error Flow

```
Service/Controller
    ↓ (throws BaseError)
Filter/Middleware
    ↓ (catches exception)
ErrorResponse Builder
    ↓ (formats response)
Logger
    ↓ (logs with severity)
HTTP Response
    ↓
Client
```

## Testing Structure

```typescript
// Unit tests
describe('NotFoundError', () => {
  it('should create error with correct properties', () => {
    const error = new NotFoundError('Not found', { id: '123' });
    expect(error.statusCode).toBe(404);
  });
});

// Integration tests
describe('GET /users/:id', () => {
  it('should return 404 for non-existent user', async () => {
    const response = await request(app)
      .get('/users/999')
      .expect(404);

    expect(response.body.error).toBe('Not Found');
  });
});
```

## Total Size

- Core files: ~18 KB
- Documentation: ~35 KB
- Examples: ~19 KB
- Total: ~72 KB

## Version

- Created: 2025-12-12
- Sprint: Sprint 1 P1
- Status: Complete
