# Migration Guide: 11.8.x → 11.9.x

## Overview

| Category | Details |
|----------|---------|
| **Breaking Changes** | None |
| **New Features** | ErrorCodeModule for centralized error handling with i18n translations |
| **Bugfixes** | None |
| **Migration Effort** | Minimal (~5 minutes for basic update, optional feature adoption) |

---

## Quick Migration (No Breaking Changes)

```bash
# Update package
npm install @lenne.tech/nest-server@11.9.x

# Verify build
npm run build

# Run tests
npm test
```

**That's it!** The ErrorCodeModule is automatically registered and provides error translations at `/api/i18n/errors/:locale`.

---

## What's New in 11.9.x

### 1. ErrorCodeModule - Centralized Error Handling with i18n

The new ErrorCodeModule provides a centralized system for error codes with internationalization support.

#### Features

- **REST API** for error translations (Nuxt i18n compatible)
- **Type-safe error codes** with `ErrorCode` constant
- **Extensible** for project-specific error codes
- **Auto-registered** in CoreModule by default

#### New REST Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/i18n/errors/de` | GET | German error translations |
| `/api/i18n/errors/en` | GET | English error translations |

#### Response Format (Nuxt i18n compatible)

```json
{
  "errors": {
    "LTNS_0001": "Benutzer wurde nicht gefunden.",
    "LTNS_0002": "Das eingegebene Passwort ist ungültig.",
    "LTNS_0100": "Sie sind nicht angemeldet.",
    "LTNS_0101": "Zugriff verweigert - Unzureichende Berechtigungen."
  }
}
```

> **Note:** The translations returned by the i18n API are user-friendly messages intended for end users. They may differ from the technical error messages used in exceptions (e.g., `#LTNS_0100: Unauthorized - User is not logged in`).

#### Error Code Ranges

| Range | Category |
|-------|----------|
| LTNS_0001-0099 | Authentication errors |
| LTNS_0100-0199 | Authorization errors |
| LTNS_0200-0299 | User errors |
| LTNS_0300-0399 | Validation errors |
| LTNS_0400-0499 | Resource errors |
| LTNS_0500-0599 | File errors |
| LTNS_0900-0999 | Internal errors |

---

## Using Error Codes in Your Code

### Basic Usage

```typescript
import { UnauthorizedException, BadRequestException } from '@nestjs/common';
import { ErrorCode } from '@lenne.tech/nest-server';

// Throw with standardized error code
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
// Response: { statusCode: 401, message: "#LTNS_0100: Unauthorized - User is not logged in" }

throw new BadRequestException(ErrorCode.VALIDATION_FAILED);
// Response: { statusCode: 400, message: "#LTNS_0300: Validation failed" }
```

### Available Error Codes

```typescript
ErrorCode.USER_NOT_FOUND          // #LTNS_0001: User not found
ErrorCode.INVALID_PASSWORD        // #LTNS_0002: Invalid password
ErrorCode.INVALID_TOKEN           // #LTNS_0003: Invalid or malformed token
ErrorCode.TOKEN_EXPIRED           // #LTNS_0004: Token has expired
ErrorCode.REFRESH_TOKEN_REQUIRED  // #LTNS_0005: Refresh token required
ErrorCode.USER_NOT_VERIFIED       // #LTNS_0006: User email not verified
ErrorCode.UNAUTHORIZED            // #LTNS_0100: Unauthorized - User is not logged in
ErrorCode.ACCESS_DENIED           // #LTNS_0101: Access denied - Insufficient permissions
ErrorCode.RESOURCE_FORBIDDEN      // #LTNS_0102: Resource access forbidden
ErrorCode.EMAIL_ALREADY_EXISTS    // #LTNS_0200: Email already registered
ErrorCode.USERNAME_ALREADY_EXISTS // #LTNS_0201: Username already taken
ErrorCode.VALIDATION_FAILED       // #LTNS_0300: Validation failed
ErrorCode.REQUIRED_FIELD_MISSING  // #LTNS_0301: Required field missing
ErrorCode.INVALID_FIELD_FORMAT    // #LTNS_0302: Invalid field format
ErrorCode.RESOURCE_NOT_FOUND      // #LTNS_0400: Resource not found
ErrorCode.RESOURCE_ALREADY_EXISTS // #LTNS_0401: Resource already exists
ErrorCode.FILE_NOT_FOUND          // #LTNS_0500: File not found
ErrorCode.FILE_UPLOAD_FAILED      // #LTNS_0501: File upload failed
ErrorCode.FILE_TYPE_NOT_ALLOWED   // #LTNS_0502: File type not allowed
ErrorCode.INTERNAL_ERROR          // #LTNS_0900: Internal server error
ErrorCode.SERVICE_UNAVAILABLE     // #LTNS_0901: Service temporarily unavailable
ErrorCode.LEGACY_AUTH_DISABLED    // #LTNS_0902: Legacy authentication is disabled
```

---

## Adding Project-Specific Error Codes (Optional)

### Scenario A: Simple Addition via Config (Recommended)

The easiest way to add project-specific error codes.

**1. Create error codes file:**

```typescript
// src/server/common/errors/project-errors.ts
import { IErrorRegistry, mergeErrorCodes } from '@lenne.tech/nest-server';

export const ProjectErrors = {
  ORDER_NOT_FOUND: {
    code: 'PROJ_0001',
    message: 'Order not found',
    translations: {
      de: 'Bestellung mit ID {orderId} wurde nicht gefunden.',
      en: 'Order with ID {orderId} was not found.',
    },
  },
  PAYMENT_FAILED: {
    code: 'PROJ_0002',
    message: 'Payment processing failed',
    translations: {
      de: 'Die Zahlung konnte nicht verarbeitet werden: {reason}',
      en: 'Payment processing failed: {reason}',
    },
  },
} as const satisfies IErrorRegistry;

// Merged error codes for type-safe usage
export const ErrorCode = mergeErrorCodes(ProjectErrors);
```

**2. Add to config.env.ts:**

```typescript
import { ProjectErrors } from './server/common/errors/project-errors';

const config = {
  // ... other config ...
  errorCode: {
    additionalErrorRegistry: ProjectErrors,
  },
};
```

**Done!** Your project errors are now available via `/api/i18n/errors/:locale`.

### Scenario B: Custom Service (For Additional Locales)

Use this when you need additional locales beyond German and English.

See [INTEGRATION-CHECKLIST.md](../src/core/modules/error-code/INTEGRATION-CHECKLIST.md) for detailed instructions.

### Scenario C: Custom Controller (For Custom Routes)

Use this when you need custom endpoints like `/codes` listing.

See [INTEGRATION-CHECKLIST.md](../src/core/modules/error-code/INTEGRATION-CHECKLIST.md) for detailed instructions.

---

## Configuration Reference

### New Config Option: errorCode

```typescript
// config.env.ts
const config: IServerOptions = {
  // ... other config ...

  /**
   * ErrorCodeModule configuration (new in 11.9.0)
   */
  errorCode: {
    /**
     * Additional error registry to merge with core LTNS_* errors
     * @optional
     */
    additionalErrorRegistry: ProjectErrors,

    /**
     * Auto-register ErrorCodeModule in CoreModule
     * Set to false to provide your own module with custom controller/service
     * @default true
     */
    autoRegister: true,
  },
};
```

---

## Compatibility Notes

### Existing Projects

- **No changes required** - ErrorCodeModule is auto-registered and provides translations immediately
- **Existing error handling** continues to work unchanged
- **New error codes** are opt-in and can be adopted gradually

### Custom Auth Implementations

If your project extends CoreAuthService or CoreAuthResolver, you can now use standardized error codes:

```typescript
// Before (still works)
throw new UnauthorizedException('Invalid password');

// After (recommended)
import { ErrorCode } from '@lenne.tech/nest-server';
throw new UnauthorizedException(ErrorCode.INVALID_PASSWORD);
```

---

## Troubleshooting

### Error translations not loading

**Symptom:** `/api/i18n/errors/de` returns 404

**Solution:** Ensure you're on version 11.9.x and the server has been restarted:

```bash
npm install @lenne.tech/nest-server@11.9.x
npm run build
npm run start:dev
```

### Custom errors not appearing

**Symptom:** Project-specific errors not in translation response

**Solution:** Verify your config.env.ts includes the additionalErrorRegistry:

```typescript
import { ProjectErrors } from './server/common/errors/project-errors';

errorCode: {
  additionalErrorRegistry: ProjectErrors,
}
```

### Route conflict with custom controller

**Symptom:** `/codes` endpoint returns locale error

**Solution:** Use a standalone controller (not extending CoreErrorCodeController). See the INTEGRATION-CHECKLIST.md for details.

---

## Module Documentation

### ErrorCodeModule

- **Integration Checklist:** [src/core/modules/error-code/INTEGRATION-CHECKLIST.md](../src/core/modules/error-code/INTEGRATION-CHECKLIST.md)
- **Reference Implementation:** `src/server/modules/error-code/`
- **Key Files:**
  - `error-codes.ts` - Core error definitions and ErrorCode constant
  - `core-error-code.service.ts` - Service for translation handling
  - `core-error-code.controller.ts` - REST controller
  - `interfaces/error-code.interfaces.ts` - Type definitions

---

## New Exports

The following are now exported from `@lenne.tech/nest-server`:

```typescript
// Error Code types and constants
export { ErrorCode } from './core/modules/error-code/error-codes';
export { LtnsErrors } from './core/modules/error-code/error-codes';
export { IErrorDefinition, IErrorRegistry, ErrorCodeKey, ErrorCodeType, RawErrorCode } from './core/modules/error-code/error-codes';
export { getAllErrorDefinitions, mergeErrorCodes } from './core/modules/error-code/error-codes';

// Module and services
export { ErrorCodeModule } from './core/modules/error-code/error-code.module';
export { CoreErrorCodeService } from './core/modules/error-code/core-error-code.service';
export { CoreErrorCodeController } from './core/modules/error-code/core-error-code.controller';

// Interfaces
export { IErrorCodeModuleConfig, IErrorTranslationResponse, SupportedLocale } from './core/modules/error-code/interfaces/error-code.interfaces';

// Config interface
export { IErrorCode } from './core/common/interfaces/server-options.interface';
```

---

## References

- [ErrorCodeModule Integration Checklist](../src/core/modules/error-code/INTEGRATION-CHECKLIST.md)
- [nest-server-starter](https://github.com/lenneTech/nest-server-starter) (reference implementation)
- [Error Code Documentation](../docs/error-codes.md) (if available)
