Skip to content
safran

Type to search. Enter opens the first result.

    Error handling

    Everything Safran raises on purpose is a SafranError with a stable code. You branch on the code, show the message and the hint, and never parse text. This page describes the error object, lists every code with the situations that produce it, and shows how failures appear inside results (BatchError, SafranWarning) when a call deliberately does not throw.

    A complete example

    The example runs offline on a fake tracker that supports only comments and search, so several codes can be provoked without a network.

    handle-errors.ts
    import { createSafran, defineProfile, isSafranError, toSafranError, type Ticket } from "@safran/core";
    import { FakeTracker, fakePlugins } from "@safran/kit/testing";
    
    const jira = new FakeTracker({
      id: "jira",
      capabilities: ["comments", "search"],
      tickets: [{ key: "PAY-1423", title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor" }],
    });
    
    await using safran = await createSafran({
      profile: defineProfile({ version: 1, company: "acme", trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }] }),
      builtinPlugins: false,
      plugins: fakePlugins({ trackers: [jira] }),
      index: false,
    });
    
    /** Returns the ticket, or undefined when there is no such ticket. Everything else is the caller's problem. */
    async function findTicket(ref: string): Promise<Ticket | undefined> {
      try {
        return await safran.tickets.get(ref);
      } catch (error) {
        if (isSafranError(error, "NOT_FOUND")) return undefined;
        throw error;
      }
    }
    
    async function describe(task: () => Promise<unknown>): Promise<string> {
      try {
        return JSON.stringify(await task());
      } catch (thrown) {
        const error = toSafranError(thrown);
        switch (error.code) {
          case "NOT_FOUND":
          case "INVALID_INPUT":
            return `ask again: ${error.format()}`;
          case "UNSUPPORTED":
            return `skip this step: ${error.message}`;
          case "AUTH_MISSING":
          case "AUTH_FAILED":
            return `fix the credentials: ${error.format()}`;
          case "RATE_LIMITED":
          case "UPSTREAM":
            return `try again later: ${error.message}`;
          case "ABORTED":
            return "cancelled";
          default:
            return `report this: ${error.code} ${error.message}`;
        }
      }
    }
    
    console.log((await findTicket("PAY-1423"))?.title);
    console.log(await findTicket("PAY-9999"));
    console.log(await describe(() => safran.tickets.get("OPS-7")));
    console.log(await describe(() => safran.tickets.history("PAY-1423")));
    console.log(await describe(() => safran.tickets.search({ text: "iade" }, { limit: 0 })));
    console.log(await describe(() => safran.code.search("refund")));
    $ bun handle-errors.ts
    Kısmi iade işlemi İstanbul şubesinde başarısız oluyor
    undefined
    ask again: No tracker recognises "OPS-7" as a ticket reference
    → Configured trackers: jira (PAY).
    skip this step: Tracker "jira" (fake) does not support history
    ask again: `limit` must be a whole number of at least 1
    → Pass a value between 1 and 500, or leave it out for the default of 50.
    skip this step: Code search is disabled for this Safran instance

    Two patterns are in it:

    • Catch narrowly. findTicket handles the one code it has an answer for and rethrows the rest. isSafranError(error, "NOT_FOUND") is a type guard, so no cast is needed.
    • Classify at the edge. describe turns any thrown value into a SafranError with toSafranError and switches on the code. The groups in the switch are the useful ones: the caller's input, a missing feature, credentials, a temporary upstream problem, cancellation, and everything else.

    The error object

    SafranError extends Error.

    MemberTypeMeaning
    codeSafranErrorCodeOne of the codes. Stable: branch on it.
    hintstring | undefinedWhat the user can do next, when there is something to do.
    detailsRecord<string, unknown> | undefinedMachine-readable context: variable, problems, status, closest, … Which keys exist depends on the error.
    format()stringThe message, and on a second line → plus the hint. What the CLI prints and what agents are shown.
    toJSON()SafranErrorJsoncode, message, hint, details. No stack, no cause. This is what JSON.stringify(error) produces.

    message, name ("SafranError"), stack and cause are the usual Error members. cause holds the original failure when Safran wrapped one (a network error, a parse error).

    error-shape.ts
    import { SafranError, isSafranError, toSafranError } from "@safran/core";
    
    const error = new SafranError("AUTH_MISSING", "Environment variable JIRA_TOKEN is not set", {
      hint: "Export JIRA_TOKEN in your shell, or put it in the .env file next to the profile.",
      details: { variable: "JIRA_TOKEN" },
    });
    
    console.log(error.format());
    console.log(JSON.stringify(error));
    console.log(isSafranError(error), isSafranError(error, "AUTH_FAILED"), error instanceof Error);
    
    console.log(toSafranError(new TypeError("fetch failed")).code);
    console.log(toSafranError(new DOMException("The operation timed out.", "TimeoutError")).code);
    console.log(toSafranError(error) === error);
    $ bun error-shape.ts
    Environment variable JIRA_TOKEN is not set
    → Export JIRA_TOKEN in your shell, or put it in the .env file next to the profile.
    {"code":"AUTH_MISSING","message":"Environment variable JIRA_TOKEN is not set","hint":"Export JIRA_TOKEN in your shell, or put it in the .env file next to the profile.","details":{"variable":"JIRA_TOKEN"}}
    true false true
    INTERNAL
    ABORTED
    true
    export class SafranError extends Error {
      declare readonly [SAFRAN_ERROR_BRAND]: true;
      readonly code: SafranErrorCode;
      readonly hint?: string;
      readonly details?: Record<string, unknown>;
      constructor(code: SafranErrorCode, message: string, options: SafranErrorOptions = {});
      /** Message plus hint, for humans and agents. */
      format(): string;
      /** Code, message, hint and details: everything a log line or a structured tool result needs. No stack, no cause. */
      toJSON(): SafranErrorJson;
    }
    
    export interface SafranErrorOptions {
      /** What the user can do about it. Shown by the CLI and returned to agents. */
      hint?: string;
      cause?: unknown;
      /** Extra machine-readable context. Must never contain secrets. */
      details?: Record<string, unknown>;
    }
    
    /** `JSON.stringify(error)` shape. A plain Error serialises without its message. */
    export interface SafranErrorJson {
      code: SafranErrorCode;
      message: string;
      hint?: string;
      details?: Record<string, unknown>;
    }

    defined in packages/kit/src/errors.ts

    isSafranError, not instanceof

    isSafranError(error, code?) is true for a SafranError, and with a code only for that code. Use it instead of error instanceof SafranError.

    The reason is practical. Two copies of the kit can be loaded in one process: a third-party plugin that bundles its own, or a linked checkout next to an installed one. instanceof compares against one copy's class and fails for errors thrown by the other. isSafranError also recognises a brand shared through the global symbol registry, so it works across copies.

    toSafranError

    toSafranError(value) turns anything that was thrown into a SafranError without losing it:

    • A SafranError is returned as it is.
    • An AbortError or TimeoutError becomes ABORTED.
    • Anything else becomes INTERNAL with the original message, and the original value as cause.

    Use it where you must handle every failure in one shape: the top of a command, a request handler, a tool result.

    Hints are for the reader, details are for the program

    message says what happened and hint says what to do. Both are written to be shown as they are, to a person in a terminal or to an agent in a tool result, so pass error.format() on rather than rewording it.

    details is for code. It can contain text that came from a third party (the HTTP client keeps the start of a failed response's body in details.body), so do not show details to a model.

    What errors never contain

    Messages, hints and details are built so that a credential cannot end up in them:

    • The HTTP client never puts header values into an error, shows request URLs without their query string, and copies only a short allow-list of response headers (retry-after, the rate-limit headers, content-type) into details.headers.
    • Output of git is scrubbed of every form of the credential before it becomes a message or a log line.
    • A profile holds the names of environment variables, so AUTH_MISSING can name the variable without revealing anything.

    Plugin authors are held to the same rule; see plugins.

    Codes

    ERROR_CODES lists them, and SafranErrorCode is their union type.

    CodeWhen it occursWhat to do
    PROFILE_INVALIDThe profile file does not exist, is not valid YAML, or does not match the schema. details.problems lists each problem with its path.Fix the profile; safran profile check shows the same list. See validation errors.
    PLUGIN_NOT_FOUNDNo registered plugin handles the type of a profile entry (the hint lists the available types); or a module under plugins: cannot be imported or exports no plugin.Correct the type, or register the plugin.
    PLUGIN_CONFIG_INVALIDA profile entry does not match its plugin's schema: a missing or misspelled field, a pasted token where a variable name belongs. Also the code of a creation error that reports several kinds of problems at once.Fix the fields named in details.problems.
    AUTH_MISSINGAn environment variable the profile names is unset or empty. details.variable is its name. Raised on the first call that needs the secret.Set the variable. See secrets.
    AUTH_FAILEDA service answered 401 (token rejected) or 403 (valid token, no permission for this resource); or git was refused by the code host.Check that the token is valid, not expired and scoped for the resource.
    NOT_FOUNDNo tracker recognises a ticket reference; a ticket, page or attachment does not exist (HTTP 404); a repo name is unknown (the hint offers the closest names); a file or repository is not in the index; a remote repository or branch is gone.Usually the input: show the hint and ask again.
    FORBIDDENUnderstood and authenticated, but refused by a local policy: the profile lists plugins: while allowProfilePlugins is false; a page is in a space outside a doc source's allow-list; a work item is in a project the tracker entry does not cover.Widen the policy in the profile if that is intended. It is not a credentials problem.
    UNSUPPORTEDThe connector cannot do this: a tracker without the capability, no tracker that can search, a code host without pull requests, a URL no doc source recognises, a code call on an instance with index: false.Skip the step or use another route. Check capabilities beforehand to avoid it.
    RATE_LIMITEDA service answered 429 and still did after the retries; or a host reported its quota as spent. details.headers may carry retry-after.Wait and retry; lower concurrency.
    UPSTREAMThe other side failed: a 5xx status, an unreachable host, a request that timed out, a response that is not JSON, a redirect to another origin, a git network failure, an embedder that returned unusable vectors.Retry later; if it persists, check the service's URL in the profile.
    INVALID_INPUTAn argument is wrong: a limit below 1, a cursor from another query, an empty query, an unknown group or tracker id, an ambiguous ticket reference, a date that is not a date, an invalid regular expression, a path outside the repository. Also: two plugins with the same kind and type, and any call on a closed instance.Fix the call. The hint states the accepted values.
    INDEX_NOT_READYThe code index exists but cannot answer: its vectors come from another embedder, it is locked by another process, or it was closed.See INDEX_NOT_READY. Usually: run safran sync.
    INCOMPATIBLE_DATAA file in the data directory was written by a newer Safran or is not what it should be: the code index, the links store, a golden set.Update Safran, or delete the file named in the message and rebuild it.
    ABORTEDThe call was cancelled: your AbortSignal fired, a timeout signal expired, or the instance was closed while the call was running.Nothing. Do not report it as a failure. See cancellation.
    INTERNALSomething Safran did not expect: a thrown value that is not a SafranError, a plugin that lists a capability without implementing it, git missing from PATH, a data directory that cannot be written.A bug or a broken environment. Report it with the message; the cause has the original error.

    How HTTP statuses become codes

    Every built-in connector talks through the same HTTP client, so the mapping is uniform:

    ResponseCodeRetried first
    401, 403AUTH_FAILEDno
    404NOT_FOUNDno
    429RATE_LIMITEDyes
    408, 425, 500, 502, 503, 504UPSTREAMyes
    any other non-2xxUPSTREAMno
    no response (network failure, per-attempt timeout)UPSTREAMyes

    "Retried" means up to three more attempts with exponential backoff, honouring Retry-After. You only see the error after the retries are spent, so retrying immediately in your own code rarely helps. A connector can refine the mapping for its service (a GraphQL API that answers 200 with an error body, for example).

    Errors inside results

    Three kinds of calls do not throw for a partial failure, because throwing would discard the part that worked. They carry the failure in their result, with the same code values, so you branch the same way.

    BatchError: one row of a report

    repos.sync and links.refresh return a report with one row per repository. A row with status: "failed" has an error:

    FieldMeaning
    codeThe same code the failure would have had as a thrown SafranError.
    messageThe same message, with credentials masked.
    hintWhat to do next, when there is something to do.
    report-failures.ts
    import { createSafran, type BatchError } from "@safran/core";
    
    await using safran = await createSafran();
    
    const report = await safran.repos.sync();
    
    const byCode = new Map<BatchError["code"], string[]>();
    for (const row of report.results) {
      if (row.status !== "failed" || row.error === undefined) continue;
      byCode.set(row.error.code, [...(byCode.get(row.error.code) ?? []), row.repo]);
    }
    
    if (byCode.has("AUTH_FAILED")) console.error(`check the code host token; affected: ${byCode.get("AUTH_FAILED")?.join(", ")}`);
    for (const repo of byCode.get("UPSTREAM") ?? []) console.error(`will retry later: ${repo}`);
    if (report.aborted) console.error("the run was cancelled; rows marked skipped were not reached");

    A cancelled batch is not an error either: the report has aborted: true.

    SafranWarning: an answer that is incomplete

    A warning says that a call succeeded but its answer does not cover everything:

    FieldMeaning
    sourceProfile entry id of the tracker or code host the warning is about.
    codeWhy it is missing: the failure's code, or UNSUPPORTED for a connector that was left out.
    messageA sentence for people.

    Where warnings appear:

    CallWarnings mean
    tickets.search → result.warningsA tracker failed or could not run this search; the items of the others are returned. See tickets.
    repos.warnings()A code host could not list its repositories, or two repositories share a name. See repositories.

    A result with warnings is a partial answer. Say so when you present it: "no matching tickets" and "no matching tickets, and one tracker could not be asked" are different facts.

    /**
     * A failure carried inside a result instead of being thrown: one row of a batch report.
     * The same fields as a `SafranError`, so callers branch on `code` here exactly as they do in a
     * `catch`.
     */
    export interface BatchError {
      code: SafranErrorCode;
      message: string;
      /** What to do next, when there is something to do. */
      hint?: string;
    }
    
    /** Something that did not stop a call but made its answer incomplete or ambiguous. */
    export interface SafranWarning {
      /** Profile entry id of the tracker or code host the warning is about. */
      source: string;
      code: SafranErrorCode;
      message: string;
    }

    defined in packages/core/src/api.ts

    Throwing your own

    Code that sits between Safran and a user (a plugin, a tool, a command) should throw SafranError too, so its failures get the same treatment:

    throw-own.ts
    import { SafranError } from "@safran/core";
    
    export function parseSprint(value: string): number {
      const sprint = Number(value);
      if (!Number.isInteger(sprint) || sprint < 1) {
        throw new SafranError("INVALID_INPUT", `"${value}" is not a sprint number`, {
          hint: "Pass the sprint as a whole number, such as 42.",
          details: { value },
        });
      }
      return sprint;
    }

    Pick the code by what the reader should do, write the message as a fact and the hint as an instruction, and keep secrets out of all three fields.

    Common mistakes

    MistakeWhy it hurts
    Matching on error.messageMessages are for people and may change. Codes are the contract.
    error instanceof SafranErrorFails across two loaded copies of the kit. Use isSafranError.
    Catching everything and returning undefinedAn expired token then looks like "no such ticket". Catch the codes you can answer and rethrow the rest.
    Logging ABORTED as an errorCancellation is the caller's own decision.
    Retrying AUTH_FAILED or INVALID_INPUTThey do not get better with time. Only RATE_LIMITED and UPSTREAM are worth a later retry.
    Dropping the hintThe hint is usually the most useful sentence. Print error.format().