> ## Documentation Index
> Fetch the complete documentation index at: https://docs.markpdf.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Manejo de errores

> Excepciones escritas en el paquete Flutter/Dart y estrategia de reintento.

# Manejo de errores

El paquete traduce cada código de error HTTP en una subclase de `MarkpdfException`.

```dart theme={null}
import 'package:markpdf/markpdf.dart';

try {
  final result = await client.convertFile(file);
} on MarkpdfException catch (e) {
  print('Conversion failed (${e.statusCode}): ${e.message}');
}
```

## Tabla de excepciones

| Estado HTTP | Clase                              | causa                                                                              |
| ----------: | ---------------------------------- | ---------------------------------------------------------------------------------- |
|     — (red) | `MarkpdfConnectionException`       | No se pudo conectar, se agotó el tiempo de espera o se produjo un error de socket. |
|       `400` | `MarkpdfBadRequestException`       | Cuerpo inválido o URL malformado.                                                  |
|       `401` | `AuthenticationException`          | Falta la clave API o no es válida.                                                 |
|       `403` | `MarkpdfForbiddenException`        | Clave sin permiso o host no autorizado de URL.                                     |
|       `413` | `PayloadTooLargeException`         | Documento, páginas o ZIP fuera de límites.                                         |
|       `415` | `MarkpdfUnsupportedMediaException` | Formato o `content-encoding` no admitido.                                          |
|       `422` | `MarkpdfVavalidationException`     | Faltan parámetros requeridos.                                                      |
|       `429` | `RateLimitException`               | Demasiadas peticiones.                                                             |
|       `5xx` | `MarkpdfServerException`           | Error de conversión en el servidor.                                                |
| — (trabajo) | `MarkpdfJobFailedException`        | El trabajo en cola (`202`) falló después de reintentos internos.                   |

Todas extienden `MarkpdfException` y exponente:

```dart theme={null}
class MarkpdfException implements Exception {
  final int? statusCode;
  final String message;
}
```

\##Capturar excepciones específicas

```dart theme={null}
import 'package:markpdf/markpdf.dart';

try {
  final result = await client.convertFile(file, options: const ConvertOptions(mode: ConversionMode.fast));
} on AuthenticationException {
  throw Exception('API key invávalida');
} on PayloadTooLargeException {
  print('Document too large; prueba con pages para dividirlo.');
} on RateLimitException catch (e) {
  print('Rate limited: ${e.message}');
} on MarkpdfVavalidationException catch (e) {
  print('Parámetros invávavalids: ${e.message}');
} on MarkpdfServerException {
  print("Conversion error; try mode: ConversionMode.balanced.");
} on MarkpdfException catch (e) {
  // catch-all for any other exceptions from SDK
  print('Error: ${e.message}');
}
```

## Reintentos automáticos

```dart theme={null}
final client = MarkpdfClient(apiKey: 'YOUR_API_KEY', maxRetries: 4);
```

* `429` y `5xx`: reintentos con retroceso exponencial y jitter. Respete `Retry-After` si el servidor lo envía.
* `4xx` diferente de `429`: **no** reintentado.
* Errores de red/tiempo de espera: reintento igual que `5xx`.

Deshabilitar los reintentos de paquetes:

```dart theme={null}
final client = MarkpdfClient(apiKey: 'YOUR_API_KEY', maxRetries: 0);
```

<Tip />

## Trabajo falvaválido

```dart theme={null}
try {
  final result = await client.convertFile(file);
} on MarkpdfJobFailedException catch (e) {
  print('Job ${e.jobId} falló: ${e.message}');
}
```

<Warning>
  `MarkpdfJobFailedException` significa que el trabajo ya agotó los reintentos del servidor interno. Volver a intentarlo desde el cliente es razonable, pero hágalo con retroceso.
</Warning>

## Mostrar errores en la interfaz de usuario

Patrón común para traducir excepciones de SDK a mensajes amigables en `Widget`:

```dart theme={null}
String friendlyMessage(Object error) {
  return switch (error) {
    AuthenticationException() => 'Configuración invávalida. Contacta soporte.',
    PayloadTooLargeException() => 'The document is too large.',
    RateLimitException() => 'Demasiadas conversiones seguidas. Intenta en unos segundos.',
    MarkpdfConnectionException() => 'Sin conexión. Revisa tu internet.',
    MarkpdfException() => 'Could not convert the document.',
    _ => 'Ocurrió un error inesperado.',
  };
}
```
