# Web3Proxy Error Handling Utilities

This directory contains utilities for standardized error handling across the application.

## Error Handling

The error handling utilities provide a consistent way to:

1. Log errors
2. Capture exceptions in Sentry with proper context
3. Return standardized error responses to clients

## Usage

### Using the Error Handler Directly

You can use the `handleError` function directly in your try/catch blocks:

```typescript
import { handleError } from '../utils/errorHandler'

fastify.get('/example', async (request, reply) => {
  try {
    // Your route logic here
    return { success: true, data: result }
  } catch (error) {
    return handleError(request, reply, error, 'endpoint/path')
  }
})
```

### Using the Route Wrapper

For more concise code, use the `createHandler` or `withErrorHandling` functions:

```typescript
import { createHandler } from '../utils/routeWrapper'

// Method 1: Using createHandler
fastify.get('/example', createHandler('endpoint/example', async (request, reply) => {
  // Your route logic here - errors are automatically caught and handled
  return { success: true, data: result }
}))

// Method 2: Using withErrorHandling
const originalHandler = async (request, reply) => {
  // Your route logic here
  return { success: true, data: result }
}

fastify.get('/example', withErrorHandling(originalHandler, 'endpoint/example'))
```

## Custom Error Types

The error handler provides several custom error types that map to appropriate HTTP status codes:

- `ValidationError`: For request validation errors (400)
- `NotFoundError`: For resource not found errors (404)
- `UnauthorizedError`: For authentication failures (401)
- `ForbiddenError`: For permission errors (403)

Example:

```typescript
import { ValidationError } from '../utils/errorHandler'

if (!isValid) {
  throw new ValidationError('Invalid input parameters')
}
```

## Best Practices

1. Always provide a meaningful endpoint string for tracking in Sentry
2. Use the appropriate error type for better error classification
3. Prefer using the route wrapper for new routes
4. Include relevant context in error messages for easier debugging 