Skip to Content

Error Handling

Learn how to handle errors in Duron

Duron provides built-in retry logic for handling transient failures. However, some errors should not be retried. Use NonRetriableError to prevent Duron from retrying steps that will fail regardless of retry attempts.

NonRetriableError

NonRetriableError is the primary error type you'll use in your actions. When a step throws this error, Duron will fail the step immediately without retrying, even if retry options are configured.

import { NonRetriableError } from 'duron/errors'

await ctx.step('validateInput', async () => {
  if (!isValid(ctx.input)) {
    throw new NonRetriableError('Invalid input')
  }
})

When to Use NonRetriableError

Use NonRetriableError for errors that won't succeed on retry:

  • Validation errors - Invalid input data
  • Authorization errors - Insufficient permissions
  • Business logic errors - Conditions that won't change
  • Permanent failures - Errors that indicate a fundamental problem

Validation Errors

Don't retry validation errors - they won't succeed on retry:

await ctx.step(
  'validateOrder',
  async () => {
    if (ctx.input.items.length === 0) {
      throw new NonRetriableError('Order must have at least one item')
    }

    if (ctx.input.total < 0) {
      throw new NonRetriableError('Order total cannot be negative')
    }
  },
  {
    retry: {
      limit: 0, // Don't retry validation
    },
  },
)

Authorization Errors

Authorization failures won't succeed on retry:

await ctx.step('checkPermissions', async () => {
  const user = await fetchUser(ctx.input.userId)

  if (!user.hasPermission('create_order')) {
    throw new NonRetriableError('User does not have permission to create orders')
  }
})

Business Logic Errors

Business logic errors indicate conditions that won't change:

await ctx.step('checkInventory', async () => {
  const product = await fetchProduct(ctx.input.productId)

  if (product.stock < ctx.input.quantity) {
    throw new NonRetriableError(`Insufficient stock. Available: ${product.stock}`)
  }
})

Converting Retriable to Non-Retriable Errors

Sometimes you want to convert a retriable error to non-retriable after multiple failures:

let attempts = 0
await ctx.step('fetchData', async () => {
  try {
    return await fetchData()
  } catch (error) {
    attempts++

    // After 3 attempts, mark as non-retriable
    if (attempts >= 3) {
      throw new NonRetriableError('Failed to fetch data after multiple attempts', {
        cause: error,
      })
    }

    throw error // Retry for now
  }
})

Error Context

Include useful context in your errors:

throw new NonRetriableError('Payment failed', {
  cause: {
    paymentId: payment.id,
    reason: payment.failureReason,
    userId: ctx.input.userId,
  },
})

Complete Example

import { defineAction } from 'duron/action'
import { NonRetriableError } from 'duron/errors'
import { z } from 'zod'

const processOrder = defineAction()({
  name: 'processOrder',
  input: z.object({
    orderId: z.string(),
    userId: z.string(),
    items: z.array(
      z.object({
        productId: z.string(),
        quantity: z.number(),
      }),
    ),
  }),
  handler: async (ctx) => {
    // Step 1: Validate input (non-retriable)
    await ctx.step(
      'validateOrder',
      async () => {
        if (ctx.input.items.length === 0) {
          throw new NonRetriableError('Order must have at least one item')
        }
      },
      {
        retry: {
          limit: 0, // Don't retry validation
        },
      },
    )

    // Step 2: Check permissions (non-retriable)
    await ctx.step('checkPermissions', async () => {
      const user = await fetchUser(ctx.input.userId)
      if (!user.hasPermission('create_order')) {
        throw new NonRetriableError('User does not have permission', {
          cause: { userId: ctx.input.userId },
        })
      }
    })

    // Step 3: Check inventory (non-retriable)
    await ctx.step('checkInventory', async () => {
      for (const item of ctx.input.items) {
        const product = await fetchProduct(item.productId)
        if (product.stock < item.quantity) {
          throw new NonRetriableError(`Insufficient stock for ${product.name}`, {
            cause: {
              productId: item.productId,
              requested: item.quantity,
              available: product.stock,
            },
          })
        }
      }
    })

    // Step 4: Process payment (retriable - network issues might resolve)
    const payment = await ctx.step('processPayment', async () => {
      return await processPayment(ctx.input)
    })

    if (!payment.success) {
      // Payment failure is non-retriable
      throw new NonRetriableError('Payment failed', {
        cause: {
          paymentId: payment.id,
          reason: payment.failureReason,
        },
      })
    }

    return { success: true, paymentId: payment.id }
  },
})

Best Practices

Use NonRetriableError for Permanent Failures

Always use NonRetriableError for errors that indicate permanent failures:

// ✅ Good: Validation errors are permanent
if (!isValid(ctx.input)) {
  throw new NonRetriableError('Invalid input')
}

// ✅ Good: Authorization errors won't change
if (!user.hasPermission('action')) {
  throw new NonRetriableError('Insufficient permissions')
}

// ✅ Good: Business logic errors
if (product.stock < quantity) {
  throw new NonRetriableError('Insufficient stock')
}

Let Transient Errors Retry

Don't use NonRetriableError for transient failures that might succeed on retry:

// ✅ Good: Network errors might succeed on retry
try {
  return await fetchData()
} catch (error) {
  if (error instanceof NetworkError) {
    throw error // Let Duron retry
  }
  throw new NonRetriableError('Permanent failure', { cause: error })
}

Include Useful Context

Provide context in error causes to help with debugging:

throw new NonRetriableError('Payment failed', {
  cause: {
    paymentId: payment.id,
    amount: ctx.input.amount,
    userId: ctx.input.userId,
    reason: payment.failureReason,
  },
})

Log Errors

Use the logger to log errors with context:

try {
  await operation()
} catch (error) {
  ctx.logger.error(
    {
      error,
      jobId: ctx.jobId,
      input: ctx.input,
    },
    'Operation failed',
  )

  // Convert to non-retriable if appropriate
  if (error instanceof ValidationError) {
    throw new NonRetriableError('Validation failed', { cause: error })
  }

  throw error // Let other errors retry
}

Error Serialization

Errors are automatically serialized and stored in the database. The serialization includes:

  • name - Error class name
  • message - Error message
  • code - Error code (for Duron errors)
  • nonRetriable - Whether the error prevents retries
  • metadata - Context metadata (jobId, stepId, actionName, etc.)
  • cause - Underlying cause (if any)
  • stack - Stack trace (if available)

This allows you to inspect errors later through the API or dashboard.

Built-in Error Types

Duron provides several built-in error types for different scenarios. All Duron errors extend the base DuronError class.

UnhandledChildStepsError

Thrown when a parent step completes with unhandled (non-awaited) child steps. This extends NonRetriableError.

import { UnhandledChildStepsError } from 'duron'

// This error is thrown automatically by Duron when:
await ctx.step('parent', async ({ step }) => {
  step('child1', async () => {
    /* ... */
  }) // Not awaited!
  step('child2', async () => {
    /* ... */
  }) // Not awaited!
  return { done: true } // Throws UnhandledChildStepsError
})

// Always await all child steps:
await ctx.step('parent', async ({ step }) => {
  await step('child1', async () => {
    /* ... */
  })
  await step('child2', async () => {
    /* ... */
  })
  return { done: true }
})

StepAlreadyExecutedError

Thrown when a job runs a step whose name was already used by another step under the same parent step (or at the top level). Use distinct names, or a dynamic step name for a step definition that runs more than once.

// This error is thrown automatically when you try to run the same step twice
await ctx.step('fetchUser', async () => {
  /* ... */
})
await ctx.step('fetchUser', async () => {
  /* ... */
}) // Throws StepAlreadyExecutedError

ActionTimeoutError

Thrown when an action exceeds its configured timeout. This is a non-retriable error.

const myAction = defineAction()({
  name: 'myAction',
  expire: 5000, // 5 second timeout
  handler: async (ctx) => {
    // If this takes longer than 5 seconds, ActionTimeoutError is thrown
    await ctx.step('slowOperation', async () => {
      await sleep(10000) // Will timeout
    })
  },
})

StepTimeoutError

Thrown when a step exceeds its configured timeout. Unlike ActionTimeoutError, this error is retriable by default.

await ctx.step(
  'fetchData',
  async () => {
    // If this takes too long, StepTimeoutError is thrown
    await fetch(url)
  },
  {
    expire: 5000, // 5 second timeout for this step
  },
)

ActionCancelError

The reason of the step signal when a running job is aborted: by client.cancelJob(), or by a graceful client.stop(). This is a non-retriable error. After cancelJob() the job ends cancelled; after a stop, a job whose handler rejects returns to the queue instead (see Releasing unfinished jobs).

// When you cancel a job, its steps' signal aborts with this error
await client.cancelJob(jobId)

WaitReadTimeoutError and WaitReadFailedError

Thrown by client.runActionAndWait() when its first read of the job's status did not finish within the Client's waitReadTimeout (WaitReadTimeoutError), or failed (WaitReadFailedError, with the read error as its cause). Both carry the job id in metadata.jobId. The job may exist and keep running: only the caller's read gave up, and the job is not cancelled.

import { WaitReadFailedError, WaitReadTimeoutError } from 'duron'

try {
  await client.runActionAndWait('sendEmail', { to: 'user@example.com' })
} catch (error) {
  if (error instanceof WaitReadTimeoutError || error instanceof WaitReadFailedError) {
    // The job may still run: look it up later with client.getJobById(error.metadata.jobId)
  }
}

Error Utility Functions

Duron exports utility functions for checking error types without using instanceof:

import {
  isDuronError,
  isNonRetriableError,
  isUnhandledChildStepsError,
  isTimeoutError,
  isCancelError,
  serializeError,
} from 'duron/errors'

try {
  await ctx.step('operation', async () => {
    /* ... */
  })
} catch (error) {
  if (isDuronError(error)) {
    console.log('Duron error code:', error.code)
    console.log('Metadata:', error.metadata)
  }

  if (isNonRetriableError(error)) {
    // Error will not be retried
  }

  if (isTimeoutError(error)) {
    // ActionTimeoutError or StepTimeoutError
  }

  if (isCancelError(error)) {
    // ActionCancelError
  }

  if (isUnhandledChildStepsError(error)) {
    console.log('Pending child steps:', error.pendingCount)
  }

  // Serialize error for storage or logging
  const serialized = serializeError(error)
}

Error Codes

Each Duron error has a code property for identification:

Error TypeCode
DuronError (base)DURON_ERROR
StepAlreadyExecutedErrorSTEP_ALREADY_EXECUTED
NonRetriableErrorNON_RETRIABLE
ActionTimeoutErrorACTION_TIMEOUT
StepTimeoutErrorSTEP_TIMEOUT
ActionCancelErrorACTION_CANCEL
UnhandledChildStepsErrorUNHANDLED_CHILD_STEPS
WaitReadTimeoutErrorWAIT_READ_TIMEOUT
WaitReadFailedErrorWAIT_READ_FAILED

On this page