> Fetch clean Markdown by appending `.md` to any page URL under https://signalwire.com/docs or requesting it with the HTTP header `Accept: text/markdown`. The root index at https://signalwire.com/docs/llms.txt lists the available documentation indexes.

# onError

> Register an agent-level hook that runs when any SWAIG tool handler throws.

[ref-agentbase]: /docs/server-sdks/reference/typescript/agents/agent-base

[functionresult]: /docs/server-sdks/reference/typescript/agents/function-result

[define-tool]: /docs/server-sdks/reference/typescript/agents/agent-base/define-tool

Register an agent-level hook that runs when any SWAIG tool handler throws. Use
it to report the failure to your error tracker and, optionally, to decide what
the caller hears. The error is always contained: a thrown handler never breaks
the live call.

The hook runs after the tool's own `onError` option, if one was set in
[`defineTool()`][define-tool].

## **Parameters**

**`handler`** `SwaigErrorHandler | undefined` — required

Called with `(error, context)`. Return a [`FunctionResult`][functionresult]
to control the response, or return nothing to fall back to the tool's
`errorMessage` or the default message. Pass `undefined` to clear the hook.

---

## **Returns**

[`AgentBase`][ref-agentbase] -- Returns `this` for method chaining.

## **Example**

```typescript {5-9}
import { AgentBase, FunctionResult } from '@signalwire/sdk';

const agent = new AgentBase({ name: 'dispatch', route: '/dispatch' });

agent.onError(async (error, context) => {
  console.error('tool failed', { tool: context.functionName, error });
  return new FunctionResult(
    "I couldn't reach the dispatch system. Let me connect you to an operator.",
  ).connect('+15551234567');
});
```