agentskit.js
Cookbook

Error boundary

Surface LLM and tool errors without crashing the UI or silently hiding failures.

Agents fail in interesting ways: timeouts, malformed tool args, provider outages, budget exceeded. Show the user something useful instead of a spinning loader that never ends.

useChat exposes error: Error | null. There is no ChatError type β€” narrow with AgentsKitError and ErrorCodes.

import { useChat } from '@agentskit/react'
import { AgentsKitError, ErrorCodes } from '@agentskit/core'

export function Chat() {
  const { messages, error, retry } = useChat({ adapter })

  return (
    <>
      {messages.map((m) => (
        <p key={m.id}>{m.content}</p>
      ))}
      {error ? <ErrorBox error={error} onRetry={retry} /> : null}
    </>
  )
}

function ErrorBox({ error, onRetry }: { error: Error; onRetry: () => void }) {
  if (error instanceof AgentsKitError) {
    if (error.code === ErrorCodes.AK_TOOL_EXEC_FAILED) {
      return (
        <p>
          A tool couldn't run. {error.hint ?? error.message}{' '}
          <button onClick={onRetry}>Try again</button>
        </p>
      )
    }
    return (
      <p>
        {error.message} <button onClick={onRetry}>Retry</button>
      </p>
    )
  }
  return <p>Something went wrong. <button onClick={onRetry}>Retry</button></p>
}

Tip

ChatReturn.error is Error | null. Use instanceof AgentsKitError and compare error.code to ErrorCodes β€” never catch (e: any) and render String(e).

Explore nearby

✎ Edit this page on GitHubΒ·Found a problem? Open an issue β†’Β·How to contribute β†’
Ask the docs
Ask anything about AgentsKit. Answers come from the docs corpus and cite their sources.