Errors

Every error, whatever the operation, has the same four members. Your program reads code and context; a person reads error.

The envelope

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: en
Myle-Request-Id: 01M803CAJ14DSK72C4MKMWBPT7

{
  "code": "core.conflict",
  "context": { "kind": "product", "name": "A0012" },
  "error": "A0012 is already used by another 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}");
}
MemberWhat it is
code What went wrong, as a stable identifier: <module>.<area>.<reason>, or core.<reason> for the generic ones. A published code is never renamed, and always comes with the same HTTP status.
context The detail, an object ({} when there is none), whose shape is fixed per code. Members may be added; ignore those you do not know.
error One sentence for a person, in English or French. It changes between versions and languages: never parse it or branch on it.
request_id The request's id in Myle's logs, the same as the Myle-Request-Id header. It stays snake_case.

Handling an error

  1. Branch on code.
  2. Read context with that code's schema (the reference lists, per operation, the codes each status can carry).
  3. On a code you do not know, fall back on the HTTP status.
  4. Show error to a person if there is one to show it to.

French or English

error follows Accept-Language: English when the header is absent or names neither language, French with Accept-Language: fr. Content-Language says which one you got. code and context do not change.

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": "La ressource a changé depuis votre lecture : relisez-la, puis réessayez."

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 and support

Log Myle-Request-Id with every failed call. When you ask for help, through the chat of the Myle app or at contact@myleapp.fr, give it: it finds the request in Myle's logs at once. A 500 never says why in its body; the cause is logged under that id.

Validation errors

An invalid body answers 422 core.validation-failed, with every invalid field at once:

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": "Some fields are invalid; see 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 is a JSON Pointer into your body, or ?name for a query parameter; code is the reason (required, must-be-positive, too-long, invalid-format, unknown-value, not-found…).

404 or 422? An unknown id in the path, or an organization the key cannot see, is 404 core.not-found, the same whether it does not exist or is not visible. An unknown id in the body is a 422 with the field code not-found.

The generic codes

StatusCodecontext
400core.bad-request: unreadable JSON, malformed parameter{}
400core.api-version-unsupported{"minimum": "YYYY-MM-DD"}
401auth.credential.missing, .invalid, .expired, .revoked{}
402core.module-required: the organization's plan lacks the module{"module": "…"}
403auth.right.missing{"right": "INVOICES_CREATE"}
403auth.api-key.organization-not-allowed: a user key narrowed to other organizations{}
403auth.session.required: an operation keys may never call{}
404core.not-found{"kind": "product", "name": "<id sent>"}
405core.method-not-allowed, with Allow{}
406core.not-acceptable: nothing matches Accept{"available": ["application/json"]}
409core.conflict: a unique value is taken{"kind": "…", "name": "…"}
409core.idempotency-key-in-use, with Retry-After{}
412core.precondition-failed: a stale If-Match{}
413core.payload-too-large{"maxBytes": 1048576}
415core.unsupported-media-type{}
422core.validation-failed{"fields": [{"path", "code"}]}
422core.idempotency-key-reused: same key, another body{}
429core.rate-limited, with Retry-After{"policy": "read"}
500core.internal-error{}
502core.bad-gateway: a service Myle depends on refused{"service": "…"}
503core.unavailable, with Retry-After{}

A 401 also carries WWW-Authenticate: Bearer. Each module adds its own codes for what a program can act on, for example billing.invoice.closed-fiscal-year; the reference lists them per operation.

What to retry