Error Handling

Discriminated unions, compensation patterns, and rescheduling.

Queuert provides only job completion — there is no built-in "failure" state. This is intentional: you control how errors are represented in your job outputs. There is no dead-letter queue either: a job that keeps throwing keeps being rescheduled, with its last error in lastAttemptError.

Discriminated Union

Return error information in your output type. process-payment completes with either a transaction ID or the reason the payment was declined:

src/error-handling.ts

/*
 * process-payment --> output { success: true, transactionId } | { success: false, error }
 */
"process-payment": {
  entry: true;
  input: { orderId: string; amountCents: number };
  output: { success: true; transactionId: string } | { success: false; error: string };
};

The processor completes the job in both cases, so a declined payment is a finished job with a typed outcome:

src/error-handling.ts

"process-payment": {
  attemptHandler: async ({ job, complete }) =>
    stateAdapter.withTransaction(async (txCtx) =>
      job.input.amountCents > 100_000
        ? complete({ ...txCtx, output: { success: false, error: "Amount exceeds limit" } })
        : complete({
            ...txCtx,
            output: { success: true, transactionId: `txn-${job.input.orderId}` },
          }),
    ),
},

The caller inspects the output to determine success or failure, and TypeScript narrows each branch on success:

src/error-handling.ts

const paymentChain = await stateAdapter.withTransaction(async (txCtx) =>
  client.createChain({
    ...txCtx,
    typeName: "process-payment",
    input: { orderId: "order-2", amountCents: 150_000 },
  }),
);
const payment = await client.awaitChain(paymentChain, { timeoutMs: 5000 });
const paymentStatus = payment.output.success
  ? `paid with ${payment.output.transactionId}`
  : `declined: ${payment.output.error}`;

Tip

This is the simplest approach and works well for most jobs. Prefer it when the caller needs to react to the outcome, or when you want the error to be part of the chain's permanent record.

Compensation

For workflows that need rollback, continue to a compensation job that undoes previous steps.

charge-card
ship-order
carrier rejects
refund-chargecompensates the charge

ship-order either completes the chain with { shipped: true } or continues with refund-charge, so the chain ends with one of the two outputs:

src/error-handling.ts

/*
 * charge-card --> ship-order --> output { shipped }
 *                     |
 *                     +-- (carrier rejects) --> refund-charge --> output { refunded }
 */
"charge-card": {
  entry: true;
  input: { orderId: string; amountCents: number };
  continueWith: { typeName: "ship-order" };
};
"ship-order": {
  input: { orderId: string; chargeId: string };
  output: { shipped: true };
  continueWith: { typeName: "refund-charge" };
};
"refund-charge": {
  input: { chargeId: string; reason: string };
  output: { refunded: true; refundId: string };
};

When the carrier rejects the order, the processor continues with the refund in the same transaction that completes ship-order:

src/error-handling.ts

"ship-order": {
  attemptHandler: async ({ job, complete }) =>
    stateAdapter.withTransaction(async (txCtx) =>
      carrierRejectedOrders.has(job.input.orderId)
        ? complete({
            ...txCtx,
            continueWith: {
              typeName: "refund-charge",
              input: { chargeId: job.input.chargeId, reason: "carrier rejected the order" },
            },
          })
        : complete({ ...txCtx, output: { shipped: true } }),
    ),
},

Rescheduling

When a job throws an error, the job is rescheduled with exponential backoff; this is what other queues call a retry. fetch-exchange-rate lets the rate provider's error propagate, and a worker runs a new attempt after the delay its backoffConfig sets:

src/error-handling.ts

"fetch-exchange-rate": {
  backoffConfig: { initialDelayMs: 10, maxDelayMs: 1000 },
  attemptHandler: async ({ job, complete }) => {
    if (job.lastAttemptError !== null) {
      previousErrors.push(job.lastAttemptError);
    }

    const rate = await fetchRate(job.input.currency);

    return stateAdapter.withTransaction(async (txCtx) =>
      complete({ ...txCtx, output: { rate } }),
    );
  },
},

For explicit control over when the next attempt runs, see Rescheduling from a Handler.

lastAttemptError

On every attempt after the first, job.lastAttemptError contains the serialized error from the previous attempt, and it is null on the first attempt. The handler above records it; use it for logging or to adjust how the next attempt behaves. When the previous attempt was reclaimed because its worker lost its lease, stopped, or no longer ran it, it holds a serialized JobAttemptReclaimedError.

  • Error object
    Stack trace (includes message). Own enumerable properties appended as JSON.
  • Plain object
    JSON-stringified
  • String
    Stored as-is

Values are truncated to 10,000 characters.

See examples/guides/src/error-handling.ts for the runnable code. See also Job Processing Reliability for engine-level safety guarantees such as the token-guarded complete and automatic reschedule, and Timeouts.

esc

Search guides, integrations and every exported symbol.

↑ ↓ to navigate↵ to open