# error

Canonical URL: https://developers.iagenify.com/sdk/agent/events/error/
Language: en

`{ type: "error", message, code }`

The run is about to fail. It is emitted just before run() rejects — so it is a notice, not a recoverable state.

Status: the run then rejects · rare · tool failures are not this

## Fields {#fields}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `message` | string |  | The error's message. |
| `code` | string |  | Its code, when it has one — `context_too_large`, `turn_failed`, `unauthorized`. |

## What is not an error event {#not-this}

| Situation | Reported as |
| --- | --- |
| A tool threw | `tool_end` with `ok: false` — the loop continues |
| A tool was refused | `tool_end` with `refused: true` |
| A turn failed and is being retried | `retry` |
| A model gave up and the next is used | `fallback` |
| A ceiling was reached | `done` with `stopReason` |

> **Almost everything that goes wrong is handled inside the loop**
>
> An error event means the loop itself could not continue — the turn failed on every model after every retry, the context will not fit, the session is not authorised. Each of those is a condition your code has to react to, not one the agent can work around.

## Handling it {#handling}

```javascript
import { IaGenifyError, NotEnoughCredits } from "iagenify";

try {
  await agent.run({ inputs, onEvent });
} catch (err) {
  if (err instanceof NotEnoughCredits) {
    // Never retried, on any model. Top up.
  } else if (err instanceof IaGenifyError && err.code === "context_too_large") {
    await agent.compact();
  } else {
    throw err;
  }
}
```

The event and the rejection carry the same thing — the event exists so an interface can show it without waiting for the promise to unwind.

## A subagent that fails does not fail the run {#task}

Its failure is emitted as an `error` carrying `parentId`, and the `task` call ends with `ok: false`. The parent carries on with that as the tool's result — a delegate that could not do its job is information, not a crash.

- [Fallback and retry](/sdk/agent/fallback-and-retry): What is tried before this.
- [Errors](/sdk/concepts/errors): The error classes.

```python
from iagenify import IaGenifyError, NotEnoughCredits

try:
    agent.run(inputs=inputs, on_event=on_event)
except NotEnoughCredits:
    pass  # Never retried, on any model. Top up.
except IaGenifyError as error:
    if error.code != "context_too_large":
        raise
    agent.compact()
```
