Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Return errors

Refuse a call with ctx.fail and a code the caller can act on, and know what callers see when something breaks.

Some calls should not succeed, such as adding to a full list. Declare the errors a handler can return, and fail with one of them when your code says no.

Declare and fail

List each error code under errors, with the type of the data it carries. Call ctx.fail with the code to refuse the call.

import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  handlers: (h) => ({
    add: h(
      { args: { text: t.string() }, errors: { Full: t.object({ limit: t.int() }) } },
      (ctx, { text }) => {
        if (ctx.db.items.count() >= 100) ctx.fail("Full", { limit: 100 });
        ctx.db.items.insert({ text });
      },
    ),
  }),
});

An error code starts with a capital letter. A code the handler did not declare fails the call as Internal instead.

What the caller sees

A declared error answers 422, with the code and its data.

{ "error": { "code": "Full", "data": { "limit": 100 } } }

Writes are undone

A call that fails keeps none of its writes, and the messages it sent are dropped. The luna is as it was before the call.

To keep the writes, pass keep: true. This suits a refusal that must leave a trace, such as counting failed attempts.

ctx.db.attempts.insert({ at: ctx.now() });
ctx.fail("WrongCode", {}, { keep: true });

Errors your code did not expect

A handler that throws anything other than ctx.fail answers 500, with the code Internal.

Luna’s own errors carry a code and a message, and their HTTP status says what kind they are. These are the most common, and Errors lists every code.

Code Status Means
Invalid 400 The arguments or the key were wrong
Unauthorized 401 The key or token was missing or wrong
NotFound 404 No such luna type, handler or luna
Overloaded 429 The luna or the key has too many calls, so retry later
QuotaExceeded 429 or 507 The environment or the organisation is over a request or storage quota
Internal 500 The handler threw
OutcomeUnknown 502 The call may or may not have run
Unavailable 503 The luna cannot answer now, so retry later
Timeout 504 The call ran past its deadline

Errors from another luna

A call to another luna that fails throws a LunaCallError. A declared error has code and data. Luna’s own errors have kind instead, and retryable is true when trying again may work.

import { LunaCallError } from "luna";

try {
  await ctx.call(Wallet, { id: ctx.key.id }).charge({ amount });
} catch (e) {
  if (e instanceof LunaCallError && e.code === "Insufficient") ctx.fail("NoFunds");
  throw e;
}

An error you do not catch fails your handler too. It keeps the same code if your handler declares it, and becomes Internal if not.

Next steps

Was this page helpful?