# Error Handling in Managing API

This document describes the centralized error handling approach used in the Managing API to ensure consistent error responses and logging, with Sentry integration for error monitoring.

## Architecture

The error handling architecture consists of:

1. **Global Error Handling Middleware**: Captures all unhandled exceptions and formats consistent responses
2. **Sentry Integration**: Sends detailed error information to Sentry for monitoring and analysis
3. **MediatR Pipeline**: Adds request context to exceptions before they reach the global middleware
4. **SentryErrorCapture Utility**: Provides methods for manually capturing errors with context

## Global Error Handling Middleware

The `GlobalErrorHandlingMiddleware` is registered in `Program.cs` and handles all unhandled exceptions:

```csharp
app.UseMiddleware(typeof(GlobalErrorHandlingMiddleware));
```

When an exception occurs, the middleware:

1. Determines the appropriate HTTP status code based on exception type
2. Logs the error with request details
3. Captures the exception in Sentry with appropriate context
4. Returns a standardized JSON error response to the client

## Sentry Integration

Sentry is integrated in two ways:

1. **Global Configuration**: Set up in `Program.cs` with environment-specific settings
2. **Error Capture**: In the global middleware and utility methods

The captured data includes:

- HTTP request details (path, method, query strings)
- Exception details (type, message, stack trace)
- Additional context from exception data
- Tags for better categorization and filtering

## MediatR Exception Handling

The `UnhandledExceptionBehaviour` in the MediatR pipeline:

1. Catches exceptions in request handlers
2. Logs the error with request details
3. Adds MediatR-specific context to the exception's Data dictionary
4. Rethrows the exception to be caught by the global middleware

This approach allows the global middleware to have full context about where the exception occurred without duplicating reporting to Sentry.

## Manual Error Reporting

For manually reporting errors to Sentry, use the `SentryErrorCapture` utility:

```csharp
// Capture an exception with context
SentryErrorCapture.CaptureException(ex, "MyService", new Dictionary<string, object> {
    { "userId", user.Id },
    { "operation", "ProcessImport" }
});

// Enrich an exception before throwing
throw SentryErrorCapture.EnrichException(new ValidationException("Invalid data"), 
    new Dictionary<string, object> {
        { "validationErrors", errors }
    });
```

## Error Response Format

The standard error response format is:

```json
{
  "statusCode": 400,
  "message": "The error message",
  "traceId": "sentry-event-id",
  "stackTrace": "Only included in non-production environments"
}
```

## Best Practices

1. **Don't catch exceptions unless necessary**: Let the global middleware handle most exceptions
2. **Add context to exceptions**: Use the Data dictionary to add context that will be captured
3. **Use appropriate exception types**: Different exception types map to different HTTP status codes
4. **Avoid sensitive data**: Never include sensitive data (passwords, tokens) in error messages or context 