> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Braian551/viax/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Handling

> Understanding Viax API errors and how to handle them

## Error Response Format

All API errors follow a consistent JSON structure:

```json theme={null}
{
  "success": false,
  "message": "Human-readable error description",
  "error": "ERROR_CODE"
}
```

<ResponseField name="success" type="boolean" required>
  Always `false` for error responses
</ResponseField>

<ResponseField name="message" type="string" required>
  Human-readable error message in Spanish
</ResponseField>

<ResponseField name="error" type="string">
  Optional error code for programmatic handling
</ResponseField>

## HTTP Status Codes

The Viax API uses standard HTTP status codes:

### Success Codes

<ResponseField name="200" type="OK">
  Request succeeded. Response includes requested data.
</ResponseField>

<ResponseField name="201" type="Created">
  Resource successfully created (not commonly used)
</ResponseField>

### Client Error Codes

<ResponseField name="400" type="Bad Request">
  Invalid request parameters or malformed JSON

  **Common causes:**

  * Missing required fields
  * Invalid data types
  * Malformed JSON
</ResponseField>

<ResponseField name="401" type="Unauthorized">
  Authentication failed or missing credentials

  **Common causes:**

  * Invalid email/password combination
  * User account does not exist
</ResponseField>

<ResponseField name="403" type="Forbidden">
  User lacks permission for the requested action

  **Common causes:**

  * Account is inactive or suspended
  * Insufficient permissions for admin endpoints
  * Driver not approved
</ResponseField>

<ResponseField name="404" type="Not Found">
  Requested resource does not exist

  **Common causes:**

  * User ID not found
  * Trip ID not found
  * Endpoint URL is incorrect
</ResponseField>

### Server Error Codes

<ResponseField name="500" type="Internal Server Error">
  Unexpected server error

  **Action:** Retry the request. If the error persists, contact support.
</ResponseField>

<ResponseField name="503" type="Service Unavailable">
  Service temporarily unavailable

  **Action:** Wait and retry with exponential backoff.
</ResponseField>

## Exception Types

The Viax client SDK defines the following exception types:

### ServerException

Thrown when the server returns an error response (HTTP 400, 500, etc.).

```dart theme={null}
class ServerException extends AppException {
  const ServerException(String message);
}
```

**Example:**

```json theme={null}
{
  "success": false,
  "message": "Email ya está registrado"
}
```

### NetworkException

Thrown when there's a network connectivity issue.

```dart theme={null}
class NetworkException extends AppException {
  const NetworkException(String message);
}
```

**Common causes:**

* No internet connection
* Request timeout
* DNS resolution failure
* Connection refused

### NotFoundException

Thrown when a resource is not found (HTTP 404).

```dart theme={null}
class NotFoundException extends AppException {
  const NotFoundException(String message);
}
```

**Example:**

```json theme={null}
{
  "success": false,
  "message": "Viaje no encontrado"
}
```

### AuthException

Thrown for authentication failures (HTTP 401).

```dart theme={null}
class AuthException extends AppException {
  const AuthException(String message);
}
```

**Example:**

```json theme={null}
{
  "success": false,
  "message": "Credenciales inválidas"
}
```

### UnauthorizedException

Thrown for authorization failures (HTTP 403).

```dart theme={null}
class UnauthorizedException extends AppException {
  const UnauthorizedException(String message);
}
```

### ValidationException

Thrown for data validation errors.

```dart theme={null}
class ValidationException extends AppException {
  const ValidationException(String message);
}
```

## Common Error Scenarios

### Invalid Credentials

```json theme={null}
{
  "success": false,
  "message": "Email o contraseña incorrectos"
}
```

**Status Code:** 401 Unauthorized

### Email Already Registered

```json theme={null}
{
  "success": false,
  "message": "Email ya está registrado"
}
```

**Status Code:** 400 Bad Request

### Missing Required Fields

```json theme={null}
{
  "success": false,
  "message": "Campo 'email' es requerido"
}
```

**Status Code:** 400 Bad Request

### Trip Not Found

```json theme={null}
{
  "success": false,
  "message": "Viaje no encontrado"
}
```

**Status Code:** 404 Not Found

### Driver Not Available

```json theme={null}
{
  "success": false,
  "message": "No hay conductores disponibles en esta área"
}
```

**Status Code:** 200 OK (success: false)

### Network Timeout

```json theme={null}
{
  "success": false,
  "message": "Tiempo de espera agotado"
}
```

Client-side exception, no HTTP response received.

## Error Handling Best Practices

<Steps>
  <Step title="Check HTTP Status">
    Always check the HTTP status code first to determine the error category
  </Step>

  <Step title="Parse Error Response">
    Parse the JSON error response to get the specific error message
  </Step>

  <Step title="Handle Gracefully">
    Display user-friendly error messages and provide actionable next steps
  </Step>

  <Step title="Log for Debugging">
    Log errors for debugging, but never expose sensitive information
  </Step>

  <Step title="Retry When Appropriate">
    Implement retry logic for network errors and 5xx server errors
  </Step>
</Steps>

## Retry Strategy

For transient errors (network issues, 503 errors), implement exponential backoff:

```dart theme={null}
Future<T> retryWithBackoff<T>(
  Future<T> Function() operation, {
  int maxAttempts = 3,
  Duration initialDelay = const Duration(seconds: 1),
}) async {
  int attempt = 0;
  while (true) {
    try {
      return await operation();
    } catch (e) {
      attempt++;
      if (attempt >= maxAttempts || !shouldRetry(e)) {
        rethrow;
      }
      await Future.delayed(initialDelay * attempt);
    }
  }
}
```

<Warning>
  **Do not retry** these errors:

  * 400 Bad Request
  * 401 Unauthorized
  * 403 Forbidden
  * 404 Not Found

  **Retry** these errors:

  * Network timeouts
  * 500 Internal Server Error
  * 503 Service Unavailable
</Warning>

## Timeout Configuration

The API has a default timeout of 30 seconds:

```dart theme={null}
static const Duration connectionTimeout = Duration(seconds: 30);
static const Duration receiveTimeout = Duration(seconds: 30);
```

Ensure your client implements appropriate timeout handling:

```dart theme={null}
try {
  final response = await client
    .post(url, body: data)
    .timeout(AppConfig.connectionTimeout);
} on TimeoutException {
  throw NetworkException('Tiempo de espera agotado');
}
```

## Error Monitoring

<Note>
  The API includes error logging and crash reporting. Enable analytics in your configuration:

  ```dart theme={null}
  static const bool enableCrashReporting = true;
  ```
</Note>

## Support

If you encounter persistent errors or unexpected behavior:

1. Check API status if monitoring is available
2. Review the documentation for the specific endpoint
3. Verify your request format matches the examples
4. Contact technical support with:
   * Timestamp of the error
   * Request details (without sensitive data)
   * Full error response
   * Steps to reproduce
