Erreurs

Toute erreur, quelle que soit l'opération, a les quatre mêmes membres. Votre programme lit code et context ; une personne lit error.

L'enveloppe

CLI

#!/usr/bin/env bash
# errors-envelope: the myle CLI (key from `myle login` or MYLE_API_KEY).
# An API error is printed on stderr as the API's object (code, context, error, request_id), with exit code 1.
# --format json: no warning on stderr, the error object alone.
if ! error=$(myle products create --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
    --number A0012 --name 'Ensilage maïs' --vat-rate 20 --format json 2>&1 >/dev/null); then
  # Branch on code; context is the code's. Show error to a person, log request_id.
  jq -r 'if .code == "core.conflict" then "\(.context.kind) \(.context.name) already exists"
         else "\(.code) \(.error) \(.request_id)" end' <<<"$error"
fi

HTTP

HTTP/1.1 409 Conflict
Content-Type: application/json
Content-Language: fr
Myle-Request-Id: 01M803CAJ14DSK72C4MKMWBPT7

{
  "code": "core.conflict",
  "context": { "kind": "product", "name": "A0012" },
  "error": "A0012 est déjà utilisé par un autre objet (product).",
  "request_id": "01M803CAJ14DSK72C4MKMWBPT7"
}

TypeScript

import { CoreConflictError, Myle, MyleApiError } from '@myleapp/myle';

const myle = new Myle();
const products = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products;

try {
  await products.create({ number: 'A0012', name: 'Ensilage maïs', vatRate: '20' });
} catch (e) {
  if (e instanceof CoreConflictError) {
    // One class per code; context is typed by the code.
    console.log(`${e.context.kind} ${e.context.name} already exists`);
  } else if (e instanceof MyleApiError) {
    // Any other API error: branch on code, show message to a person, log requestId.
    console.error(e.status, e.code, e.message, e.requestId);
  } else {
    throw e;
  }
}

Python

from myle import CoreConflictError, Myle, MyleApiError

myle = Myle()
products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

try:
    products.create(number="A0012", name="Ensilage maïs", vat_rate="20")
except CoreConflictError as e:
    # One class per code; context is typed by the code.
    print(f"{e.context.kind} {e.context.name} already exists")
except MyleApiError as e:
    # Any other API error: branch on code, show message to a person, log request_id.
    print(e.status, e.code, e.message, e.request_id)

Go

package main

import (
    "context"
    "errors"
    "fmt"
    "log"
    "os"

    myle "github.com/myleapp/myle-go"
)

func main() {
    client := myle.NewClient()
    products := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products

    _, err := products.Create(context.Background(), &myle.ProductCreateParams{Number: "A0012", Name: "Ensilage maïs", VatRate: "20"})
    var conflict *myle.CoreConflictError
    var apiErr *myle.APIError
    switch {
    case errors.As(err, &conflict):
        // One type per code; Context is typed by the code.
        fmt.Printf("%s %s already exists\n", conflict.Context.Kind, conflict.Context.Name)
    case errors.As(err, &apiErr):
        // Any other API error: branch on Code, show Message to a person, log RequestID.
        fmt.Fprintln(os.Stderr, apiErr.Status, apiErr.Code, apiErr.Message, apiErr.RequestID)
    case err != nil:
        log.Fatal(err)
    }
}

Java

import fr.myleapp.myle.CoreConflictException;
import fr.myleapp.myle.MyleApiException;
import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.ProductCreateParams;
import fr.myleapp.myle.Products;

public class Example {
    public static void main(String[] args) {
        MyleClient client = MyleClient.builder().build();
        Products products = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products();

        try {
            products.create(ProductCreateParams.builder().number("A0012").name("Ensilage maïs").vatRate("20").build());
        } catch (CoreConflictException e) {
            // One class per code; context() is typed by the code.
            System.out.println(e.context().kind() + " " + e.context().name() + " already exists");
        } catch (MyleApiException e) {
            // Any other API error: branch on code, show apiMessage to a person, log requestId.
            System.err.println(e.status() + " " + e.code() + " " + e.apiMessage() + " " + e.requestId());
        }
    }
}

Scala

import fr.myleapp.myle.{CoreConflictError, MyleApiError, MyleClient}
import fr.myleapp.myle.models.CreateProduct

object ErrorsEnvelope {
  def main(args: Array[String]): Unit = {
    val myle = MyleClient()
    val products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

    try products.create(CreateProduct(number = "A0012", name = "Ensilage maïs", vatRate = "20"))
    catch {
      case e: CoreConflictError =>
        // One class per code; context is typed by the code.
        println(s"${e.context.kind} ${e.context.name} already exists")
      case e: MyleApiError =>
        // Any other API error: branch on code, show message to a person, log requestId.
        System.err.println(s"${e.status} ${e.code} ${e.message} ${e.requestId.getOrElse("")}")
    }
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;
use Myle\Exception\ApiException;
use Myle\Exception\CoreConflictException;

$myle = new Client();
$products = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products;

try {
    $products->create(number: 'A0012', name: 'Ensilage maïs', vatRate: '20');
} catch (CoreConflictException $e) {
    // One class per code; context() is typed by the code.
    echo "{$e->context()->kind} {$e->context()->name} already exists\n";
} catch (ApiException $e) {
    // Any other API error: branch on errorCode, show the message to a person, log requestId.
    echo $e->status, ' ', $e->errorCode, ' ', $e->getMessage(), ' ', $e->requestId, "\n";
}

C#

using Myle;

using var client = new MyleClient();
var products = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products;

try
{
    await products.CreateAsync(new ProductCreateParams { Number = "A0012", Name = "Ensilage maïs", VatRate = "20" });
}
catch (CoreConflictException e)
{
    // One class per code; Context is typed by the code.
    Console.WriteLine($"{e.Context.Kind} {e.Context.Name} already exists");
}
catch (MyleApiException e)
{
    // Any other API error: branch on Code, show Message to a person, log RequestId.
    Console.Error.WriteLine($"{e.Status} {e.Code} {e.Message} {e.RequestId}");
}
MembreCe que c'est
code Ce qui ne va pas, sous forme d'identifiant stable : <module>.<zone>.<raison>, ou core.<raison> pour les codes génériques. Un code publié n'est jamais renommé et vient toujours avec le même statut HTTP.
context Le détail, un objet ({} s'il n'y en a pas), dont la forme est fixée pour chaque code. Des membres peuvent s'ajouter ; ignorez ceux que vous ne connaissez pas.
error Une phrase pour une personne, en français ou en anglais. Elle change d'une version et d'une langue à l'autre : ne l'analysez jamais, ne décidez jamais d'après elle.
request_id L'identifiant de la requête dans les journaux de Myle, le même que l'en-tête Myle-Request-Id. Il garde son orthographe snake_case.

Traiter une erreur

  1. Décidez d'après code.
  2. Lisez context avec le schéma de ce code (la référence liste, pour chaque opération, les codes que chaque statut peut porter).
  3. Pour un code que vous ne connaissez pas, repliez-vous sur le statut HTTP.
  4. Affichez error à une personne, s'il y a quelqu'un à qui l'afficher.

Français ou anglais

error suit Accept-Language : l'anglais quand l'en-tête est absent ou ne nomme aucune des deux langues, le français avec Accept-Language: fr. Content-Language dit laquelle vous avez reçue. code et context ne changent pas.

CLI

#!/usr/bin/env bash
# errors-language: the myle CLI (key from `myle login` or MYLE_API_KEY).
# --accept-language fr: only error changes; code and context stay the same.
org=organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d
product=product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d
# The ETag is a header: -i --format json prints {status, headers, body}.
etag=$(myle products retrieve "$product" --organization "$org" -i --format json | jq -r .headers.etag)
if ! error=$(myle products update "$product" --organization "$org" \
    --name 'Ensilage maïs, vrac' --if-match "$etag" --accept-language fr --format json 2>&1 >/dev/null); then
  jq -r '"\(.code) \(.error)"' <<<"$error"   # core.precondition-failed La ressource a changé…
fi

HTTP

"error": "The resource has changed since you read it: read it again, then retry."

TypeScript

import { CorePreconditionFailedError, Myle } from '@myleapp/myle';

// Sends Accept-Language: fr. Only message changes; code and context stay the same.
const myle = new Myle({ acceptLanguage: 'fr' });
const products = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products;

const product = await products.get('product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d');
try {
  await products.update(product.id, { name: 'Ensilage maïs, vrac' }, { ifMatch: product });
} catch (e) {
  if (!(e instanceof CorePreconditionFailedError)) throw e;
  console.log(e.code, e.message); // core.precondition-failed La ressource a changé…
}

Python

from myle import CorePreconditionFailedError, Myle

# Sends Accept-Language: fr. Only message changes; code and context stay the same.
myle = Myle(accept_language="fr")
products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

product = products.get("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d")
try:
    products.update(product.id, name="Ensilage maïs, vrac", if_match=product)
except CorePreconditionFailedError as e:
    print(e.code, e.message)  # core.precondition-failed La ressource a changé…

Go

package main

import (
    "context"
    "errors"
    "fmt"
    "log"

    myle "github.com/myleapp/myle-go"
)

func main() {
    // Sends Accept-Language: fr. Only Message changes; Code and Context stay the same.
    client := myle.NewClient(myle.WithAcceptLanguage("fr"))
    products := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products
    ctx := context.Background()

    product, err := products.Get(ctx, "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d")
    if err != nil {
        log.Fatal(err)
    }
    _, err = products.Update(ctx, product.ID, &myle.ProductUpdateParams{Name: myle.String("Ensilage maïs, vrac")}, myle.IfMatch(product))
    var stale *myle.CorePreconditionFailedError
    if errors.As(err, &stale) {
        fmt.Println(stale.Code, stale.Message) // core.precondition-failed La ressource a changé…
    } else if err != nil {
        log.Fatal(err)
    }
}

Java

import fr.myleapp.myle.CorePreconditionFailedException;
import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.Product;
import fr.myleapp.myle.ProductUpdateParams;
import fr.myleapp.myle.Products;
import fr.myleapp.myle.RequestOptions;

public class Example {
    public static void main(String[] args) {
        // Sends Accept-Language: fr. Only the message changes; code and context stay the same.
        MyleClient client = MyleClient.builder().acceptLanguage("fr").build();
        Products products = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products();

        Product product = products.get("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d");
        try {
            products.update(product.id(),
                    ProductUpdateParams.builder().name("Ensilage maïs, vrac").build(),
                    RequestOptions.builder().ifMatch(product).build());
        } catch (CorePreconditionFailedException e) {
            System.out.println(e.code() + " " + e.apiMessage()); // core.precondition-failed La ressource a changé…
        }
    }
}

Scala

import fr.myleapp.myle.{CorePreconditionFailedError, IfMatch, MyleClient, MyleConfig, Patch}
import fr.myleapp.myle.models.UpdateProduct

object ErrorsLanguage {
  def main(args: Array[String]): Unit = {
    // Sends Accept-Language: fr. Only message changes; code and context stay the same.
    val myle = MyleClient(MyleConfig(acceptLanguage = Some("fr")))
    val products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

    val product = products.get("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d")
    try products.update(product.id, UpdateProduct(name = Patch("Ensilage maïs, vrac")), ifMatch = IfMatch(product))
    catch {
      case e: CorePreconditionFailedError =>
        println(s"${e.code} ${e.message}") // core.precondition-failed La ressource a changé…
    }
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;
use Myle\Exception\CorePreconditionFailedException;

// Sends Accept-Language: fr. Only the message changes; code and context stay the same.
$myle = new Client(acceptLanguage: 'fr');
$products = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products;

$product = $products->get('product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d');
try {
    $products->update($product->id, name: 'Ensilage maïs, vrac', ifMatch: $product);
} catch (CorePreconditionFailedException $e) {
    echo $e->errorCode, ' ', $e->getMessage(), "\n"; // core.precondition-failed La ressource a changé…
}

C#

using Myle;

// Sends Accept-Language: fr. Only Message changes; Code and Context stay the same.
using var client = new MyleClient(new MyleClientOptions { AcceptLanguage = "fr" });
var products = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products;

var product = await products.GetAsync("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d");
try
{
    await products.UpdateAsync(product.Id, new ProductUpdateParams { Name = "Ensilage maïs, vrac" },
        new RequestOptions { IfMatch = product });
}
catch (CorePreconditionFailedException e)
{
    Console.WriteLine($"{e.Code} {e.Message}"); // core.precondition-failed La ressource a changé…
}

request_id et assistance

Gardez Myle-Request-Id dans vos journaux pour chaque appel en échec. Quand vous demandez de l'aide, par le chat de l'application Myle ou à contact@myleapp.fr, donnez-le : il retrouve aussitôt la requête dans les journaux de Myle. Une erreur 500 ne dit jamais pourquoi dans son corps ; la cause est journalisée sous cet identifiant.

Erreurs de validation

Un corps invalide répond 422 core.validation-failed, avec tous les champs invalides d'un coup :

CLI

#!/usr/bin/env bash
# errors-validation: the myle CLI (key from `myle login` or MYLE_API_KEY).
# A comma is not a decimal string: the CLI sends the amount as it is, and the API names every invalid field.
if ! error=$(myle products create --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
    --number A0042 --name 'Paille de blé, botte' --vat-rate 10 \
    -d 'unitPrice[amount]=4,50' -d 'unitPrice[currency]=EUR' --format json 2>&1 >/dev/null); then
  # A JSON Pointer into the body and a reason per field.
  jq -r '.context.fields[]? | "\(.path) \(.code)"' <<<"$error"   # /unitPrice/amount invalid-format
fi

JSON

{
  "code": "core.validation-failed",
  "context": {
    "fields": [
      { "path": "/vatRate", "code": "required" },
      { "path": "/unitPrice/amount", "code": "invalid-format" }
    ]
  },
  "error": "Des champs sont invalides ; voir context.fields.",
  "request_id": "01M803CAJ14DSK72C4MKMWBPT7"
}

TypeScript

import { CoreValidationFailedError, Myle } from '@myleapp/myle';

const myle = new Myle();
const products = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products;

try {
  await products.create({
    number: 'A0042',
    name: 'Paille de blé, botte',
    unitPrice: { amount: '4,50', currency: 'EUR' }, // a comma: not a decimal string
    vatRate: '10',
  });
} catch (e) {
  if (!(e instanceof CoreValidationFailedError)) throw e;
  // Every invalid field at once: a JSON Pointer into the body and a reason.
  for (const field of e.context.fields) console.log(field.path, field.code); // /unitPrice/amount invalid-format
}

Python

from myle import CoreValidationFailedError, Myle

myle = Myle()
products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

try:
    products.create(
        number="A0042",
        name="Paille de blé, botte",
        unit_price={"amount": "4,50", "currency": "EUR"},  # a comma: not a decimal string
        vat_rate="10",
    )
except CoreValidationFailedError as e:
    # Every invalid field at once: a JSON Pointer into the body and a reason.
    for field in e.context.fields:
        print(field.path, field.code)  # /unitPrice/amount invalid-format

Go

package main

import (
    "context"
    "errors"
    "fmt"
    "log"

    myle "github.com/myleapp/myle-go"
)

func main() {
    client := myle.NewClient()
    products := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products

    _, err := products.Create(context.Background(), &myle.ProductCreateParams{
        Number:    "A0042",
        Name:      "Paille de blé, botte",
        UnitPrice: myle.Value(myle.Money{Amount: "4,50", Currency: "EUR"}), // a comma: not a decimal string
        VatRate:   "10",
    })
    var invalid *myle.CoreValidationFailedError
    if errors.As(err, &invalid) {
        // Every invalid field at once: a JSON Pointer into the body and a reason.
        for _, field := range invalid.Context.Fields {
            fmt.Println(field.Path, field.Code) // /unitPrice/amount invalid-format
        }
    } else if err != nil {
        log.Fatal(err)
    }
}

Java

import fr.myleapp.myle.CoreValidationFailedContextField;
import fr.myleapp.myle.CoreValidationFailedException;
import fr.myleapp.myle.Money;
import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.ProductCreateParams;
import fr.myleapp.myle.Products;

public class Example {
    public static void main(String[] args) {
        MyleClient client = MyleClient.builder().build();
        Products products = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products();

        try {
            products.create(ProductCreateParams.builder()
                    .number("A0042")
                    .name("Paille de blé, botte")
                    .unitPrice(new Money("4,50", "EUR")) // a comma: not a decimal string
                    .vatRate("10")
                    .build());
        } catch (CoreValidationFailedException e) {
            // Every invalid field at once: a JSON Pointer into the body and a reason.
            for (CoreValidationFailedContextField field : e.context().fields()) {
                System.out.println(field.path() + " " + field.code()); // /unitPrice/amount invalid-format
            }
        }
    }
}

Scala

import fr.myleapp.myle.{CoreValidationFailedError, MyleClient}
import fr.myleapp.myle.models.{CreateProduct, Money}

object ErrorsValidation {
  def main(args: Array[String]): Unit = {
    val myle = MyleClient()
    val products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

    try {
      products.create(
        CreateProduct(
          number = "A0042",
          name = "Paille de blé, botte",
          unitPrice = Some(Money(amount = "4,50", currency = "EUR")), // a comma: not a decimal string
          vatRate = "10"
        )
      )
    } catch {
      case e: CoreValidationFailedError =>
        // Every invalid field at once: a JSON Pointer into the body and a reason.
        for (field <- e.context.fields) println(s"${field.path} ${field.code}") // /unitPrice/amount invalid-format
    }
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;
use Myle\Exception\CoreValidationFailedException;

$myle = new Client();
$products = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products;

try {
    $products->create(
        number: 'A0042',
        name: 'Paille de blé, botte',
        unitPrice: ['amount' => '4,50', 'currency' => 'EUR'], // a comma: not a decimal string
        vatRate: '10',
    );
} catch (CoreValidationFailedException $e) {
    // Every invalid field at once: a JSON Pointer into the body and a reason.
    foreach ($e->context()->fields as $field) {
        echo $field->path, ' ', $field->code, "\n"; // /unitPrice/amount invalid-format
    }
}

C#

using Myle;

using var client = new MyleClient();
var products = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products;

try
{
    await products.CreateAsync(new ProductCreateParams
    {
        Number = "A0042",
        Name = "Paille de blé, botte",
        UnitPrice = new Money { Amount = "4,50", Currency = "EUR" }, // a comma: not a decimal string
        VatRate = "10",
    });
}
catch (CoreValidationFailedException e)
{
    // Every invalid field at once: a JSON Pointer into the body and a reason.
    foreach (var field in e.Context.Fields) Console.WriteLine($"{field.Path} {field.Code}"); // /unitPrice/amount invalid-format
}

path est un JSON Pointer dans votre corps, ou ?nom pour un paramètre de requête ; code est la raison (required, must-be-positive, too-long, invalid-format, unknown-value, not-found…).

404 ou 422 ? Un identifiant inconnu dans le chemin, ou une organisation que la clé ne voit pas, donne 404 core.not-found, la même réponse qu'elle n'existe pas ou ne soit pas visible. Un identifiant inconnu dans le corps donne un 422 avec le code de champ not-found.

Les codes génériques

StatutCodecontext
400core.bad-request : JSON illisible, paramètre mal formé{}
400core.api-version-unsupported{"minimum": "YYYY-MM-DD"}
401auth.credential.missing, .invalid, .expired, .revoked{}
402core.module-required : la formule de l'organisation n'a pas le module{"module": "…"}
403auth.right.missing{"right": "INVOICES_CREATE"}
403auth.api-key.organization-not-allowed : une clé utilisateur restreinte à d'autres organisations{}
403auth.session.required : une opération interdite aux clés{}
404core.not-found{"kind": "product", "name": "<identifiant envoyé>"}
405core.method-not-allowed, avec Allow{}
406core.not-acceptable : rien ne correspond à Accept{"available": ["application/json"]}
409core.conflict : une valeur unique est déjà prise{"kind": "…", "name": "…"}
409core.idempotency-key-in-use, avec Retry-After{}
412core.precondition-failed : un If-Match périmé{}
413core.payload-too-large{"maxBytes": 1048576}
415core.unsupported-media-type{}
422core.validation-failed{"fields": [{"path", "code"}]}
422core.idempotency-key-reused : même clé, autre corps{}
429core.rate-limited, avec Retry-After{"policy": "read"}
500core.internal-error{}
502core.bad-gateway : un service dont Myle dépend a refusé{"service": "…"}
503core.unavailable, avec Retry-After{}

Un 401 porte aussi WWW-Authenticate: Bearer. Chaque module ajoute ses propres codes pour ce sur quoi un programme peut agir, par exemple billing.invoice.closed-fiscal-year ; la référence les liste pour chaque opération.

Quoi réessayer