# Credora Error Handling Guide

## Overview
This guide provides comprehensive documentation for the error handling system implemented in the Credora application. The system ensures consistent error responses, proper logging, and user-friendly feedback across all modules.

## Error Handling Architecture

### Custom Exceptions
The application uses custom exception classes for different types of errors:

#### 1. BusinessLogicException
- **Purpose**: Business rule violations and domain logic errors
- **Log Level**: WARNING
- **HTTP Status**: 400 (Bad Request)
- **Error Code Format**: `BUSINESS_RULE_VIOLATION`

#### 2. ValidationException
- **Purpose**: Form validation failures
- **Log Level**: INFO
- **HTTP Status**: 422 (Unprocessable Entity)
- **Error Code Format**: `VALIDATION_FAILED`

#### 3. AuthorizationException
- **Purpose**: Access control violations
- **Log Level**: WARNING
- **HTTP Status**: 403 (Forbidden)
- **Error Code Format**: `AUTHORIZATION_FAILED`

#### 4. NotFoundException
- **Purpose**: Resource not found errors
- **Log Level**: INFO
- **HTTP Status**: 404 (Not Found)
- **Error Code Format**: `RESOURCE_NOT_FOUND`

### Exception Handler
Located in `app/Exceptions/Handler.php`, the exception handler:
- Maps exceptions to appropriate HTTP responses
- Logs errors with context information
- Provides structured JSON responses for API calls
- Handles both web and API error responses

## Error Response Formats

### API Error Response Structure
```json
{
  "success": false,
  "message": "Human-readable error message",
  "error_code": "MACHINE_READABLE_ERROR_CODE",
  "errors": {
    "field_name": ["Specific field error messages"]
  },
  "timestamp": "2024-01-01T12:00:00Z"
}
```

### Web Error Response
- Flash messages for user feedback
- Redirects with error context
- Consistent styling across all pages

## Validation System

### Form Request Classes
All complex validation is handled through dedicated form request classes:

#### StoreClientRequest
- Validates client registration data
- Custom messages for user-friendly feedback
- File upload validation (photos, documents)

#### StoreLoanRequest
- Loan application validation
- Business rule enforcement (amount limits, dates)
- Guarantor and collateral validation

#### UpdateLoanRequest
- Partial update validation for loans
- Flexible validation rules for updates

#### StoreSavingsAccountRequest
- Savings account creation validation
- Interest rate and balance constraints

### Validation Rules
- **Required Fields**: All mandatory fields validated
- **Data Types**: Numeric, string, date validations
- **Constraints**: Min/max values, length limits
- **Uniqueness**: Email, phone, ID number uniqueness
- **File Uploads**: Size, type, and format restrictions

## Logging Strategy

### Log Levels
- **ERROR**: System errors, unexpected exceptions
- **WARNING**: Business rule violations, authorization failures
- **INFO**: Validation failures, not found resources
- **DEBUG**: Detailed debugging information

### Context Logging
All logs include relevant context:
- User ID and role
- Request information (method, path, parameters)
- Error details and stack traces
- Business operation identifiers

### Audit Logging
Critical business operations are logged for compliance:
- Loan approvals and disbursements
- Client deletions
- Financial transactions
- User role changes

## Testing Error Scenarios

### Validation Tests
Comprehensive test suites validate:
- Required field validation
- Data type constraints
- Business rule enforcement
- Error message formatting
- API response structures

### Error Handling Tests
Tests ensure proper error handling for:
- Invalid input data
- Business rule violations
- Authorization failures
- Resource not found scenarios
- System exceptions

## Best Practices

### For Developers

#### 1. Exception Usage
```php
// Business logic errors
throw new BusinessLogicException(
    'Cannot approve loan with pending documents',
    'LOAN_MISSING_DOCUMENTS'
);

// Validation errors
throw new ValidationException(
    'Loan validation failed',
    'LOAN_VALIDATION_FAILED',
    $validator->errors()->toArray()
);
```

#### 2. Form Request Classes
```php
public function store(StoreLoanRequest $request)
{
    // Validation automatically handled
    $validated = $request->validated();

    // Proceed with business logic
}
```

#### 3. Error Logging
```php
$this->logBusiness('warning', 'Loan approval failed', [
    'loan_id' => $loan->id,
    'reason' => 'Insufficient collateral'
]);
```

### For API Consumers
- Check `success` field for operation status
- Use `error_code` for programmatic error handling
- Display `message` to users
- Use `errors` object for field-specific validation messages

## Error Codes Reference

### Business Logic Errors
- `CLIENT_HAS_ACTIVE_LOANS`: Cannot delete client with active loans
- `LOAN_NOT_PENDING_FOR_CANCELLATION`: Only pending loans can be cancelled
- `INSUFFICIENT_FUNDS`: Account has insufficient balance

### Validation Errors
- `CLIENT_VALIDATION_FAILED`: Client data validation failed
- `LOAN_VALIDATION_FAILED`: Loan data validation failed
- `SAVINGS_ACCOUNT_VALIDATION_FAILED`: Savings account validation failed

### Authorization Errors
- `INSUFFICIENT_PERMISSIONS`: User lacks required permissions
- `ROLE_ACCESS_DENIED`: Role-based access restriction

### Not Found Errors
- `CLIENT_NOT_FOUND`: Specified client does not exist
- `LOAN_NOT_FOUND`: Specified loan does not exist
- `ACCOUNT_NOT_FOUND`: Specified account does not exist

## Maintenance

### Adding New Exceptions
1. Create new exception class extending `BaseException`
2. Update `Handler.php` to map the exception
3. Add error codes to documentation
4. Create tests for the new exception type

### Updating Validation Rules
1. Modify form request class rules
2. Update custom messages
3. Add tests for new validation scenarios
4. Update API documentation

### Monitoring and Alerts
- Monitor error logs for patterns
- Set up alerts for critical errors
- Review error rates and user feedback
- Regularly update error handling based on user reports

## Future Enhancements

### Planned Improvements
- Error tracking with Sentry integration
- User-friendly error pages for web interface
- Error rate monitoring and alerting
- Internationalization of error messages
- API versioning for error response formats

### API Error Response Versioning
Future API versions may include:
- Additional metadata fields
- Error categorization
- Suggested actions for resolution
- Links to relevant documentation
