Skip to content

Error Handling

Understand error types, HTTP status codes, and implement robust retry strategies.

Error Types

The SDK throws typed errors you can catch and handle precisely. The first three errors below extend PeppolError, so catching that class matches them and the base class itself. Runtime failures sit outside that hierarchy. The SDK throws the base class directly for invalid config and from waitFor(), the directory and the webhook helpers.

PeppolValidationError
Local validation failed, so the invoice was never sent. Read error.validation.errors for field paths and messages.
PeppolProtocolError
The gateway returned a 2xx body without a required field. The error carries field and a serialised responseBody, truncated after 2,000 characters. Report it instead of retrying in a loop.
PeppolApiError
The gateway returned a response the SDK could not accept: usually a 4xx or 5xx, or a 2xx body that is not JSON. It always carries statusCode. Its responseBody is the raw response body for an HTTP error, or an SDK note when a successful body could not be parsed as JSON. retryAfterMs is undefined unless the status is 429 and the response carries a readable Retry-After. code reads the response body's code field and can be undefined when a route puts its machine code in error instead.
Runtime failures
Failed connections reject with TypeError; a timeout or aborted request rejects with an Error named AbortError. The SDK retries them when its policy allows, then rethrows them unchanged. Keep a final else branch that rethrows.
import {
  Peppol,
  PeppolError,
  PeppolValidationError,
  PeppolProtocolError,
  PeppolApiError,
} from "@getpeppr/sdk";

const peppol = new Peppol({ apiKey: "sk_live_..." });

try {
  const result = await peppol.invoices.send(invoiceData);
  console.log(`Success: ${result.id}`);

} catch (error) {
  if (error instanceof PeppolValidationError) {
    // Local validation failed — invoice never sent.
    // The details live on `validation`, not on the error itself.
    console.error("Validation errors:");
    for (const e of error.validation.errors) {
      console.error(`  ${e.field}: ${e.message}`);
    }

  } else if (error instanceof PeppolProtocolError) {
    // A 2xx body the SDK cannot honestly parse (SDK 4.0.0).
    // Not caused by your payload — report it rather than looping on it.
    console.error(`Missing "${error.field}": ${error.message}`);
    console.error(error.responseBody);  // serialised, truncated past 2000 chars

  } else if (error instanceof PeppolApiError) {
    // The gateway answered something the SDK could not accept.
    // Usually a 4xx/5xx — but also a 2xx whose body is not JSON.
    console.error(`API error [${error.statusCode}]: ${error.message}`);
    console.error(error.code);          // may be undefined — some routes
                                        // put the code in `error` instead
    console.error(error.responseBody);  // raw error body, or an SDK note for invalid 2xx

  } else if (error instanceof PeppolError) {
    // The base class is thrown directly too: bad config, waitFor, directory.
    console.error(`SDK error: ${error.message}`);

  } else {
    // Not ours at all: a failed connection rejects with the runtime's
    // TypeError, a timeout or abort with an Error named AbortError. Neither is a
    // PeppolError, so this branch has to exist.
    throw error;
  }
}

HTTP Status Codes

The API uses standard HTTP status codes. Here are the ones you'll encounter:

HTTP status codes returned by the API
StatusMeaning
200Success — request completed.
201Created — the invoice was accepted for transmission. Delivery is asynchronous: follow it with webhooks or GET /v1/invoices/{id}.
202Accepted — the request was accepted; remaining steps (verification, webhook notification) continue after the response.
204No Content — success with an empty response body (e.g. a delete, or an accepted send).
302Found — redirect, used by the newsletter confirm and unsubscribe links.
400Bad Request — invalid parameters or validation error.
401Unauthorized — missing or invalid API key.
403Forbidden — your API key is valid but lacks the required scope.
404Not Found — resource doesn't exist.
405Method Not Allowed — the resource exists but this verb is not supported; e.g. transports are managed by the provider (transports.managed_by_provider).
409Conflict — the request is valid but the resource is not in the right state.
410Gone — the resource existed and is yours, but its content is no longer retained: the original UBL of a received document, removed 90 days after receipt, or earlier when a Platform contract's exit window closes. The document's details stay readable. Not retryable.
413Payload Too Large — the request is rejected when its declared Content-Length exceeds the route's cap, or when its actual bytes cross it: 1 MB, or 4 MB where a document travels in the body. Chunked requests and requests with a missing or under-declared Content-Length are still measured. Above roughly 4.5 MB this 413 is not ours: the hosting platform refuses the body before our code runs and answers plain text with none of the Getpeppr-* headers — no getpeppr request id and no result code, only the platform's own x-vercel-id — see Responses getpeppr did not write.
422Unprocessable Entity — business-rule gate failed, such as identity verification or send readiness.
429Too Many Requests — rate limit exceeded (see Rate Limits).
500Server Error — retry with exponential backoff.
502Bad Gateway — an upstream getpeppr depends on failed. Usually retryable; some need support.
501Not Implemented — the operation is intentionally unavailable on the provider; e.g. draft invoices do not exist (there is no draft state to send).
503Service Unavailable — an upstream dependency is temporarily unavailable, or the provider asked to retry later. Usually retryable; if the provider capability is not configured, contact support.
422 Validation Error
{
  "error": "invalid_base_quantity",
  "message": "baseQuantity must be a finite number greater than zero.",
  "field": "lines[0].baseQuantity",
  "rule": "PEPPOL-EN16931-R121"
}
404 Not Found
{
  "error": "Invoice not found"
}

Pre-send Compliance Gates

The Peppol network validates documents after your provider accepts them, so a non-compliant invoice would otherwise return 201 and then fail asynchronously, hours later, with no way for you to notice. getpeppr runs those checks up front instead and returns a 422 before the document leaves — every code below names the rule it enforces (a network rule, or a provider requirement where the network has none), so you can look it up rather than guess. The last six rows are the exception: refusals our network provider returns at submission (see the note under the table).

Pre-send compliance error codes
CodeMeaning / next step
invalid_country_codeA country field is present but is not a code the network accepts. The message names the exact field and echoes what we received. Case and surrounding spaces are repaired for you — "nl" is fine; "NLD" and country names are not.
country_rule_violationA national rule for the supplier's country is not met. The code field carries the rule id: an official Peppol rule (for example NL-R-003) or, when the requirement comes from our access-point provider rather than the network, a provider code (STORECOVE-NO-SENDER-PAIR for Norwegian senders). docs links to the page that explains it: our fix guide when we have one (for example the NL-R-003 guide or the Norwegian sender identifiers guide), otherwise the official rule page.
peppol_identity_incompleteYour account has no registered Peppol identifier, so a production send is refused before the invoice is read. Sender tax mismatches use the local codes sender_tax_identifier_missing and outside_scope_sender_has_tax_identifier; both are refused before document submission and covered by the sender tax identity guide.
unsupported_payment_meansThe payment means cannot be routed over Peppol by our provider. Cheques (20) and generic bank-account transfers (42) have no route; the message lists the codes that do.
payment_mandate_requiredDirect debit (49 or 59) requires a mandate reference getpeppr cannot yet send, and the network rejects such invoices (rule PEPPOL-EN16931-R061). Use a credit transfer — 30, or 58 for SEPA — with paymentIban.
payment_account_requiredA credit transfer (30, or 58 for SEPA) needs the account to pay into, and the network rejects such invoices without it (rule BR-61). Provide a non-empty paymentIban. A blank value counts as missing.
unit_code_invalidA line's unit is not a unit code the network accepts (rule BR-CL-23: UN/ECE Recommendation 20 or 21). The response carries field with the line (for example lines[1].unit) and rule: "BR-CL-23"; the value is not echoed back. The aliases listed on the unit field ("hours", "kg", "unit"…) are resolved first. Some retired codes our provider would otherwise accept and rewrite are refused here, such as PK: use XPK (package) or C62 (one) instead. The alias "pack" resolves to XPK.
invalid_provider_tax_rateStorecove rejected vatRate for the seller legal entity's tax country at the invoice date. The response carries field: "vatRate", rule: "provider_tax_rate_catalogue", and this locally-authored safe message; no provider text or invoice value is echoed. Check the rate or send with the legal entity registered for the intended tax jurisdiction.
recipient_identifier_format_invalidThe network provider refused the recipient identifier in to.peppolId: its value does not match the format required for its scheme. The response carries field: "to.peppolId" and a message written by getpeppr; the identifier is not echoed back. Check that the scheme code is the right one for this identifier and that the value is written exactly as the recipient registered it.
recipient_identifier_check_digit_invalidThe network provider refused the recipient identifier in to.peppolId because it fails the check digit of its scheme (for example the modulo-97 check of a Belgian enterprise number), so it is not a valid identifier under that scheme. This is usually a typing error. The response carries field: "to.peppolId" and a message written by getpeppr; the identifier is not echoed back. Check the number with the recipient, and that the scheme code is the right one for it. A well-formed identifier that is simply not registered gets a different answer: the provider could not send the invoice to the recipient.
order_reference_requiredThe recipient's scheme is 9915, which our network provider reads as the Austrian public administration (AT:GOV), and the invoice carries no purchase order reference. Set orderReference to the order reference of the ordering public body; the response carries field: "orderReference". In the sandbox, a 9915 test identity can send but must never be addressed: send test invoices to 9925:BE0314595348 instead (see choosing a test identity).
provider_field_invalidThe network provider refused one or more fields against the format it accepts: a value outside its list (an unknown currency), an empty or too short value (a one-letter street or postal code, an empty line description), a value too long (a phone number over 24 characters), or a value in the wrong format (a date that is not YYYY-MM-DD). The message names each field as you sent it, for example to.postalCode is empty or too short, and field carries the first one; the values themselves are not echoed back. Correct the fields and send the invoice again.
sender_country_not_servedThe network provider refused the send (the invoice itself or, on a first send, the creation of your legal entity), getpeppr could not identify a field to fix, and the sender's legal entity is in a country getpeppr does not serve yet (see the countries page). The provider applies each sender country's own rules, and our API may not expose the fields they require, so the refusal may not be fixable from your request. The response carries country (the country code of the legal entity that sends, or the from.country you declared when no legal entity exists yet), contact and docs; nothing else from the invoice is echoed back. Write to hello@getpeppr.dev and we will tell you where we stand for your country. This code only replaces the generic refusal: a refusal getpeppr can explain keeps its own code, and a send the provider accepts is never refused on this ground: its 201 carries senderCountryNotice instead, on POST /v1/invoices and on POST /v1/invoices/import (result.senderCountryNotice with @getpeppr/sdk 6.6.0 and later; older versions drop the field). senderCountryNotice also carries the same information before you send: on GET /v1/identity for your own legal entity, and on POST /v1/validate/server also for a sub-tenant named in sender. POST /v1/validate/ubl and GET /v1/invoices/{id} do not carry it: the first judges a document and knows no sender, the second describes a document already sent.

The last six rows are not up-front checks: invalid_provider_tax_rate, recipient_identifier_format_invalid, recipient_identifier_check_digit_invalid, order_reference_required, provider_field_invalid and sender_country_not_served are refusals our network provider returns synchronously when the invoice is submitted. getpeppr recognises the first five and answers in its own words; the sixth is a refusal it could not explain, from a sender in a country it does not serve yet. All six still arrive as a 422 before anything is delivered, but no Peppol BIS rule names them.

POST /v1/validate/server reports gateway-owned findings in its countryRules array without sending anything. It does not run Storecove validation; read providerSendability: "not_checked" and do not treat valid: true as proof that the provider will accept a later send. Its senderCountryNotice is non-null when the sender's legal entity is in a country getpeppr does not serve yet.
422 Invalid country code
{
  "error": "invalid_country_code",
  "message": "to.country must be a country code the Peppol network accepts (2 letters, e.g. \"NL\"). Received: \"NLD\". The network rejects any other form (rule BR-CL-14)."
}
422 Country rule violation
{
  "error": "country_rule_violation",
  "code": "NL-R-003",
  "message": "Dutch suppliers must include a KVK or OIN number. Register one on the Peppol identity page (https://console.getpeppr.dev/peppol-identity), scheme \"0106\" for KVK or \"0190\" for OIN — the Peppol network rejects Dutch invoices without it (rule NL-R-003).",
  "docs": "https://getpeppr.dev/docs/error-handling/nl-r-003/"
}

Platform Errors

Platform accounts use a master key to manage sub-tenants and send on their behalf. These endpoints add a few multi-tenant error semantics on top of the generic API errors above.

Status codes

Platform-specific HTTP status codes
StatusMeaning
403Authenticated key is not a master key, or lacks the required legal_entities:* scope.
403platform_exit_read_only — your platform contract has ended. For 30 days after termination, or 60 days after a termination for abandonment (the exit window, until exitEndsAt in the body), your production master key can still read and export documents and legal entities, and archive a legal entity; sending, importing, creating or attesting a legal entity, and marking an invoice are refused. After the window the key stops working (401).
404Sub-tenant is unknown, disabled, malformed, or belongs to another platform. getpeppr returns 404 instead of 403 to prevent resource enumeration. On a send, a sender.legalEntityId that is not a getpeppr id answers error: "malformed_resource_id", and its message tells you to send your own reference as sender.externalSubTenantId. Every other miss answers error: "not_found" with one sentence, whatever the cause. Both bodies carry a message to show a human.
409Operation conflicts with the sub-tenant lifecycle, for example requesting attestation too early or after the customer already attested.
422Sending is blocked by a business gate. Check the code field to decide what your UI should show.
502Attestation email delivery failed. Retrying can mint a fresh authorisation link.

Send-as gate codes

When POST /v1/invoices includes sender, a 422 response uses error: "peppol_identity_not_verified" with one of these code values:

Send-as gate error codes
CodeMeaning / next step
verification_pendingRegistry verification has not completed yet. Poll the legal entity or wait for a lifecycle webhook.
unsupported_schemeAutomatic verification is unavailable for this identifier scheme. Do not keep polling. In the sandbox, test sends with a separate 9915 sub-tenant (not for Dutch, Danish, Swedish, Norwegian, Greek or Icelandic suppliers, see choosing a test identity); for a real company, contact support before sending.
verification_failedRegistry verification failed. Inspect the legal entity status or the legal_entity.verification_failed webhook.
registration_failedNetwork registration (SMP publication) failed — with or without a registry verification behind it (a registryless test identity can fail here too). Inspect the legal entity status or the legal_entity.registration_failed webhook.
attestation_requiredProduction customer authorisation is required before sending. Request attestation and wait for the customer to authorise.
peppol_identity_expiredThe authorisation window expired. Request a new attestation.
provisioningSub-tenant is attested but still being registered on the network. Wait until the legal entity becomes active.
sending_suspendedA send-only legal entity is suspended: its receiving elsewhere was not found, was lost or cannot be verified, or getpeppr blocked it. The result code is invoices.sender_sending_suspended and the reasons are in suspension.reasons. Contact support.

When the gate runs on your own account identity — any standard key, or a master key without a customer sender to resolve — the same 422 peppol_identity_not_verified can also carry name_mismatch — the declared company name does not match the name on your Legal Entity — or one of three codes for an identity that is verified but not registered on the network yet: smp_not_registered — publication is in progress, or will be retried automatically; address_held_elsewhere — another Peppol provider still holds the address, so ask it to remove it: getpeppr registers it automatically once it is released (see Switching provider); smp_registration_failed — the network refused the registration and retrying will not change that, so contact support.

Treat legal_entity.verification_failed as a lifecycle webhook, not as a retryable HTTP failure. Your UI should map it to the customer record via subTenantId and show the remediation path.
400 Invalid sender
{
  "error": "sender requires exactly one of legalEntityId or externalSubTenantId"
}
404 Not a getpeppr id
{
  "error": "malformed_resource_id",
  "message": "sender.legalEntityId is not a getpeppr legal entity id. Use the id getpeppr returned when the sub-tenant legal entity was created. To identify the sub-tenant by your own reference, send it as sender.externalSubTenantId instead."
}
404 Sender not found
{
  "error": "not_found",
  "message": "No active sub-tenant legal entity of this platform account matches this sender in this environment. Check sender.legalEntityId or sender.externalSubTenantId, and that the legal entity was created with a key of the same environment."
}
422 Send-as gate
{
  "error": "peppol_identity_not_verified",
  "code": "attestation_required",
  "message": "Sub-tenant attestation is required before sending in production.",
  "docs": "https://getpeppr.dev/docs/onboarding/verification"
}

Retry Strategies

Transient failures and network timeouts are retried for you, with exponential backoff — you configure that policy rather than writing it. The SDK retries 429, 500, 502, 503 and 504 — but the status is only the fallback. When a response carries Getpeppr-Retryable, that header decides instead, in both directions: a few 409 conflicts are retried because they resolve on their own, and some 5xx results are not, because they never will. One deliberate exception: on a 5xx it will not replay a POST sent without an Idempotency-Key, because an unacknowledged write may already have landed. A 429 is different — the request was refused before it was processed, so replaying it is safe with or without a key.

Most 4xx answers need a fix to the request rather than a retry, but not all of them: a few 409 conflicts say Retry shortly in the message, because they mean an identical request is still in flight. Read the message before deciding.

Best Practices

  • Retry 429 and 5xx — a rate limit clears on its own; most other client errors need a fix
  • Honour Retry-After — when a 429 carries it, wait that many seconds; a rate limit raised by the provider rather than by us arrives without it, so keep your own backoff as the fallback
  • Exponential backoff — what the SDK already does between attempts: double the wait each time, plus jitter so parallel clients do not retry in lockstep
  • Cap the attempts — the SDK stops after 3 retries by default
  • Tell support the route, the status and roughly when — the route template rather than the URL you called, since a directory path carries the identifier in it, and error messages sometimes quote one too. Authentication failures are deliberately not logged, so for a 401 say what you were trying to do instead
Pass an idempotencyKey in the request options to make retries safe. Resending the same invoice with the same key never sends it twice: you get the original 201 with the same document id, or, while another attempt under that key is still running, a retryable 409 (idempotency.concurrent_request) — retry later with the same key. A rate limit sends nothing; after a 5xx or a timeout the invoice may or may not have gone out, so resend the same invoice with the same key: you get its 201 if it did, never a second copy. A corrected invoice is a new send: give it a new key. Once we have tried to send an invoice, its key stays bound to it even if the network refuses it. Reusing a key for a different request is rejected with 422 idempotency_key_reuse — use a new key for each distinct send.
The key has to be one we can actually look up, and this is checked twice. A blank key — an empty string, or one made only of spaces — never leaves the SDK: it is refused as a validation error before any request is sent. Sent over plain HTTP, it is refused by the gateway with 400 idempotency_key_blank — behind authentication, rate limiting and the production gates, so a request failing one of those gets that failure instead. A transport strips the whitespace at the edges of a header value, so a blank key reaches us empty, and a key that cannot protect anything is worse than no key at all — you would believe you were covered. This matters most when you derive keys from your own data, where an empty field or a padded reference can produce one without you noticing. If you do not need idempotency for a request, omit the header rather than sending it empty. Padding around a real key stays harmless: a key written as " inv-42 " is sent as inv-42, which is what the wire carried anyway.
retry.ts
import { randomUUID } from "node:crypto";
import { Peppol, PeppolApiError, type InvoiceInput } from "@getpeppr/sdk";

// The SDK already retries 429, 500, 502, 503 and 504 with exponential
// backoff. Tune it here rather than wrapping it in a loop of your own —
// a loop around a client that retries multiplies the calls, it does not
// make the send more likely to land.
const peppol = new Peppol({
  apiKey: "sk_live_...",
  retry: { maxRetries: 3 },  // the default
});

// Your own persistence, next to the invoice record — never inside the invoice
// you send: the key must not change the body it protects. Returns the stored
// key, creating it on the first call only.
declare function getOrCreateSendKey(invoiceId: string, create: () => string): Promise<string>;

async function send(invoiceId: string, invoice: InvoiceInput) {
  // One key per send: created once, stored BEFORE the first attempt, and
  // reused on every retry — including after a crash and a restart. The retry
  // then gets the first attempt's result instead of sending a second invoice.
  // Keep the invoice identical until you have an answer: a different body
  // under the same key is refused. Never derive the key from the invoice
  // number alone: two of your customers can both have an "INV-1".
  const idempotencyKey = await getOrCreateSendKey(invoiceId, () => randomUUID());

  try {
    // Without a key the SDK refuses to replay a POST — it cannot tell
    // "never sent" from "sent, answer lost". With one, it retries safely.
    return await peppol.invoices.send(invoice, { idempotencyKey });
  } catch (error) {
    if (!(error instanceof PeppolApiError)) throw error;

    // Everything retryable has already been retried by here. What is left
    // needs a decision, not another attempt.
    console.error(`send failed: ${error.statusCode}`, error.responseBody);
    throw error;
  }
}