Skip to content
75 changes: 74 additions & 1 deletion website/docs/getting-started/errors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,80 @@
sidebar_position: 7
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Manejo de errores

La API responde los errores en JSON y usa códigos de estado HTTP estándar. Para manejar errores de forma programática, usa `code`: es un string estable y predecible.

`message` está pensado para lectura humana. Hoy los mensajes de la API se devuelven en español. Pueden cambiar para mejorar claridad o soportar localización, así que no deberían usarse para branching de lógica.
`message` está pensado para lectura humana y puede devolverse en español o inglés. Puede cambiar para mejorar claridad, así que no debería usarse para branching de lógica.

## Idioma de los mensajes

En API V2, envía `Accept-Language: en` para recibir en inglés los mensajes de error definidos por Facturapi. Usa `es` para español. Se aceptan variantes regionales como `en-US` y `es-MX`, además de preferencias con prioridad como `es;q=0.5, en;q=0.9`. Sin el header o sin un idioma compatible, la API usa español.

El idioma se decide en cada petición y no depende del idioma del usuario o de la organización. La localización cambia `message` y los mensajes catalogados de `errors[].message`; los códigos, paths, status HTTP y demás campos permanecen iguales. Los mensajes originales del SAT/PAC y los mensajes legacy no catalogados conservan su idioma original.

Los SDKs ya permiten configurar headers para todas las peticiones de una instancia:

<Tabs groupId="codeExamples">
<TabItem value="js" label="Node.js" default>

```javascript
const facturapi = new Facturapi('TU_API_KEY', {
headers: { 'Accept-Language': 'en' },
});
```

</TabItem>
<TabItem value="php" label="PHP">

```php
$facturapi = new Facturapi('TU_API_KEY', [
'httpClient' => new GuzzleHttp\Client([
'headers' => ['Accept-Language' => 'en'],
]),
]);
```

</TabItem>
<TabItem value="java" label="Java">

```java
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder()
.header("Accept-Language", "en")
.build()))
.build();

Facturapi facturapi = new Facturapi(
FacturapiConfig.builder("TU_API_KEY")
.httpClient(httpClient)
.build());
```

</TabItem>
<TabItem value="cs" label="C#">

```csharp
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en");
var facturapi = FacturapiClient.CreateWithCustomHttpClient(
"TU_API_KEY", httpClient);
```

</TabItem>
<TabItem value="curl" label="cURL">

```bash
curl 'https://www.facturapi.io/v2/customers' \
-H 'Authorization: Bearer TU_API_KEY' \
-H 'Accept-Language: en'
```

</TabItem>
</Tabs>

## Objeto de error

Expand Down Expand Up @@ -143,6 +212,8 @@ Esta lista es la referencia documentada de códigos raíz públicos de la API. P
| `page_too_large` | La página solicitada excede el límite permitido. |
| `payload_too_large` | El payload excede el tamaño máximo permitido. |

Cuando el servidor conoce el límite, `payload_too_large` lo incluye entre paréntesis, p. ej. `El payload excede el tamaño máximo permitido (100KB).`

### TaxInfoValidationCode

Estos códigos describen errores de información fiscal validados por Facturapi. Cuando la validación fiscal de un cliente u organización detecta un solo problema, aparece en `code`. Las validaciones de entrada y el endpoint de validación de información fiscal de un cliente los devuelven en `errors[].code`.
Expand Down Expand Up @@ -266,6 +337,8 @@ Estos códigos describen errores de información fiscal validados por Facturapi.
| `global_invoice_too_many_items` | El periodo contiene más de 5,000 recibos abiertos. Envía `limit_to_max_receipts` para facturar hasta 5,000 por llamada o usa rangos de fechas o subconjuntos de recibos. |
| `invalid_global_invoice_period` | El rango de fechas debe estar dentro del mismo periodo de facturación: `{period}`. |

En `invalid_global_invoice_period`, `{period}` identifica el periodo con un valor estable (`year`, `day`, `week`, `fortnight`, `month` o `two_months`) y se muestra en el idioma de la respuesta, p. ej. `año` o `year`, `bimestre` o `two-month period`.

### RetentionErrorCode

| Código | Descripción |
Expand Down
4 changes: 2 additions & 2 deletions website/docs/getting-started/install.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ Usando Maven:
<dependency>
<groupId>io.facturapi</groupId>
<artifactId>facturapi-java</artifactId>
<version>1.0.0</version>
<version>2.2.0</version>
</dependency>
```

Usando Gradle:

```gradle
implementation("io.facturapi:facturapi-java:1.0.0")
implementation("io.facturapi:facturapi-java:2.2.0")
```

</TabItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,80 @@
sidebar_position: 7
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Error handling

The API returns errors as JSON and uses standard HTTP status codes. For programmatic error handling, use `code`: it is a stable, predictable string.

`message` is meant for humans. Today, API messages are returned in Spanish. They may change to improve clarity or support localization, so avoid using them for branching logic.
`message` is meant for humans and can be returned in Spanish or English. It may change to improve clarity, so avoid using it for branching logic.

## Message language

In API V2, send `Accept-Language: en` to receive Facturapi-defined error messages in English. Use `es` for Spanish. Regional variants such as `en-US` and `es-MX` are supported, as are weighted preferences such as `es;q=0.5, en;q=0.9`. Missing or unsupported language preferences fall back to Spanish.

The language is selected per request and does not depend on the user or organization language. Localization changes `message` and cataloged `errors[].message` values; codes, paths, HTTP status, and all other fields remain unchanged. Original SAT/PAC messages and uncataloged legacy messages retain their original language.

The SDKs already support configuring headers for every request made by a client instance:

<Tabs groupId="codeExamples">
<TabItem value="js" label="Node.js" default>

```javascript
const facturapi = new Facturapi('YOUR_API_KEY', {
headers: { 'Accept-Language': 'en' },
});
```

</TabItem>
<TabItem value="php" label="PHP">

```php
$facturapi = new Facturapi('YOUR_API_KEY', [
'httpClient' => new GuzzleHttp\Client([
'headers' => ['Accept-Language' => 'en'],
]),
]);
```

</TabItem>
<TabItem value="java" label="Java">

```java
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder()
.header("Accept-Language", "en")
.build()))
.build();

Facturapi facturapi = new Facturapi(
FacturapiConfig.builder("YOUR_API_KEY")
.httpClient(httpClient)
.build());
```

</TabItem>
<TabItem value="cs" label="C#">

```csharp
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en");
var facturapi = FacturapiClient.CreateWithCustomHttpClient(
"YOUR_API_KEY", httpClient);
```

</TabItem>
<TabItem value="curl" label="cURL">

```bash
curl 'https://www.facturapi.io/v2/customers' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-H 'Accept-Language: en'
```

</TabItem>
</Tabs>

## Error object

Expand Down Expand Up @@ -143,6 +212,8 @@ This list is the documented reference for public root API codes. We may add new
| `page_too_large` | The requested page exceeds the allowed limit. |
| `payload_too_large` | The request payload exceeds the maximum allowed size. |

When the server knows the limit, `payload_too_large` includes it in parentheses, e.g. `The payload exceeds the maximum allowed size (100KB).`

### TaxInfoValidationCode

These codes describe tax-information errors validated by Facturapi. When a customer or organization tax-information validation detects a single issue, it appears in `code`. Input validations and the customer tax-information validation endpoint return them in `errors[].code`.
Expand Down Expand Up @@ -266,6 +337,8 @@ These codes describe tax-information errors validated by Facturapi. When a custo
| `global_invoice_too_many_items` | The period contains more than 5,000 open receipts. Send `limit_to_max_receipts` to invoice up to 5,000 per request, or use smaller date ranges or receipt subsets. |
| `invalid_global_invoice_period` | The date range must be within the same billing period: `{period}`. |

For `invalid_global_invoice_period`, `{period}` identifies the period with a stable value (`year`, `day`, `week`, `fortnight`, `month`, or `two_months`) and is rendered in the response language, e.g. `año`/`year` or `bimestre`/`two-month period`.

### RetentionErrorCode

| Code | Description |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ Using Maven:
<dependency>
<groupId>io.facturapi</groupId>
<artifactId>facturapi-java</artifactId>
<version>1.0.0</version>
<version>2.2.0</version>
</dependency>
```

Using Gradle:

```gradle
implementation("io.facturapi:facturapi-java:1.0.0")
implementation("io.facturapi:facturapi-java:2.2.0")
```

</TabItem>
Expand Down
8 changes: 6 additions & 2 deletions website/openapi_v2.en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ info:

The secret key you use to authenticate will determine both the environment in which the invoice will be created (Test or Live), as well as the organization to use as the issuer of your invoice or as the owner of the resource you request to create.

Send `Accept-Language: en` for English Facturapi error messages, or
`Accept-Language: es` for Spanish (the default). Regional variants and `q`
priorities are supported. External SAT/PAC messages retain their original language.
See [Error handling](https://docs.facturapi.io/en/docs/getting-started/errors)
for the full contract and examples for every SDK.

tags:
- name: tools
x-displayName: Tools
Expand Down Expand Up @@ -3685,8 +3691,6 @@ paths:
description: Filters issued or received invoices.
- in: query
name: invoice_types
style: form
explode: false
schema:
type: array
uniqueItems: true
Expand Down
8 changes: 6 additions & 2 deletions website/openapi_v2.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ info:
(Test o Live), así como la organización a utilizar como emisor
de tu factura, o bien como dueña del recurso que solicites crear.

Envía `Accept-Language: en` para recibir mensajes de error de Facturapi en inglés,
o `Accept-Language: es` para español (predeterminado). Se admiten variantes regionales
y prioridades `q`. Los mensajes externos SAT/PAC conservan su idioma original.
Consulta [Manejo de errores](https://docs.facturapi.io/docs/getting-started/errors)
para el contrato completo y ejemplos con cada SDK.

tags:
- name: tools
x-displayName: Herramientas
Expand Down Expand Up @@ -3911,8 +3917,6 @@ paths:
description: Filtra facturas emitidas o recibidas.
- in: query
name: invoice_types
style: form
explode: false
schema:
type: array
uniqueItems: true
Expand Down
Loading