# FerroError and its subclasses

Every database failure Ferro raises is catchable by type. The tree is DBAPI-shaped, rooted at `FerroError`:

```text
FerroError
├── InterfaceError          the database interface was misused
├── OperationalError        the database or its environment failed
├── DataError               a value could not be decoded or converted
├── IntegrityError          a constraint rejected the statement
│   ├── UniqueViolationError
│   ├── ForeignKeyViolationError
│   ├── NotNullViolationError
│   └── CheckViolationError
├── ModelDoesNotExist       (also a LookupError)
├── InstanceNotLoaded
├── SettingsError           the project configuration is missing a key, malformed, or contradicts itself
└── MigrationRefused        a migration call refused; .report says how far it got
    ├── PendingMigrationsError
    ├── DatabaseAheadError
    └── RunRefused          a migration run, or connect(auto_migrate=True) on a tracked database, refused
        ├── AlreadyTrackedError
        └── AppliedAboveBaselineError
```

`ForeignKeyViolationError` covers every foreign-key rejection: a dangling insert, and deleting a row still referenced by a foreign-key column declared `Field(foreign_key=..., on_delete="RESTRICT")`. Catch the type, not a SQLSTATE. On PostgreSQL 17 that RESTRICT delete reports `23503`; PostgreSQL 18 reports `23001` (`restrict_violation`). Both are this class. `exc.sqlstate` is the raw driver code; Ferro does not rewrite it.

Catch a duplicate insert without matching driver text:

```python
from ferro import UniqueViolationError

try:
    await User(email="taylor@example.com").save()
except UniqueViolationError as exc:
    print(exc.sqlstate)      # SQLSTATE "23505" on Postgres, result code "2067" on SQLite
    print(exc.constraint)    # violated constraint name (Postgres only)
    print(exc.driver_message)  # original driver text, for logs
```

The same pattern applies to table checks declared in `__ferro_checks__`. A row that violates the predicate raises `CheckViolationError`:

```python
from ferro import CheckViolationError

try:
    await Pair.create(left="both", right="set")
except CheckViolationError as exc:
    print(exc.constraint)  # "ck_pair_at_most_one_side" on Postgres
```

`ModelDoesNotExist` is raised by primary-key lookups such as `Model.get(pk)` when no row matches; use `Model.get_or_none(pk)` to get `None` instead. It is also raised by `save()` on a persisted instance whose row no longer exists (see [Saving: INSERT or UPDATE](<https://ferro-orm.x54.sh/guide/mutations/#saving-insert-or-update>)). It is a `LookupError` too, so an `except LookupError` handler still catches it.

`SettingsError` is raised by `FerroSettings` and every call that reads the project configuration; its message names the key to add or move, the line to write, or the variable to set.

A refused migration call raises [`MigrationRefused`](<https://ferro-orm.x54.sh/api/migrations/#ferro.migrations.MigrationRefused>) or one of its subclasses; see [Errors](<https://ferro-orm.x54.sh/api/migrations/#errors>) in the migrations reference. Its `.report` says how far the call got:

```python
import ferro.migrations
from ferro.migrations import MigrationRefused

try:
    await ferro.migrations.up()
except MigrationRefused as exc:
    print(exc)          # what refused, and the command that fixes it
    print(exc.report)   # what the run applied before it stopped
```

An auto-migrate pass (`connect(auto_migrate=True)`, `ferro.migrate()`, `ferro.create_tables()`) that fails partway raises its usual error, also with `.report` set: the [`PassReport`](<https://ferro-orm.x54.sh/api/connection/#ferro.PassReport>) of what committed before the failure.

## FerroError

```python
FerroError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `Exception`

The root of every exception Ferro raises for database work.

Catch it to handle any database failure, or a subclass to handle one kind.

Examples:

```python
from ferro import UniqueViolationError

try:
    await Author.create(name="Ada King", email="ada@example.com")
except UniqueViolationError as error:
    assert error.sqlstate == "2067"
else:
    raise AssertionError("expected UniqueViolationError")
```

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `driver_message` | `str \| None` | The database driver's own message, or `None` when the error did not come from the database. |
| `sqlstate` | `str \| None` | The backend's error code, or `None` when the driver reports none. |
| `constraint` | `str \| None` | The violated constraint's name on Postgres, or `None` (SQLite does not report it). |

### driver\_message

```python
driver_message: str | None = driver_message
```

The database driver's own message, or `None` when the error did not come from the database.

### sqlstate

```python
sqlstate: str | None = sqlstate
```

The backend's error code, or `None` when the driver reports none.

On Postgres it is the five-character SQLSTATE, such as `"23505"`; on SQLite the extended result code, such as `"2067"`.

### constraint

```python
constraint: str | None = constraint
```

The violated constraint's name on Postgres, or `None` (SQLite does not report it).

## InterfaceError

```python
InterfaceError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `FerroError`

The database interface was misused.

Raised for problems on the client side of the conversation: operating on an unknown or uninitialized connection name, driver protocol errors, or invalid connection configuration.

## OperationalError

```python
OperationalError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `FerroError`

The database or its environment failed.

Raised for failures outside the program's control: the server is unreachable, a connection pool timed out or is closed, or an I/O or TLS error interrupted the conversation.

## DataError

```python
DataError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `FerroError`

A value could not be decoded or converted.

Raised when a fetched value cannot be decoded into the expected Python type or a bound value cannot be represented for the column type. Also raised, on both databases, when a write overflows while computing a generated column or a check's arithmetic (`a * b` past `bigint`); the message names the column or check. Any other out-of-range error from the database is an `OperationalError`.

## IntegrityError

```python
IntegrityError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `FerroError`

A database constraint rejected the statement.

## UniqueViolationError

```python
UniqueViolationError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `IntegrityError`

A `UNIQUE` or `PRIMARY KEY` constraint rejected the statement.

## ForeignKeyViolationError

```python
ForeignKeyViolationError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `IntegrityError`

A `FOREIGN KEY` constraint rejected the statement.

Includes a parent delete blocked by `Field(foreign_key=..., on_delete="RESTRICT")`. PostgreSQL 18 reports SQLSTATE `23001` for that case; PostgreSQL 17 reports `23503`. `sqlstate` is the raw driver code.

## NotNullViolationError

```python
NotNullViolationError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `IntegrityError`

A `NOT NULL` constraint rejected the statement.

## CheckViolationError

```python
CheckViolationError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `IntegrityError`

A `CHECK` constraint rejected the statement.

Raised when a check's condition is false for the row. A check whose arithmetic overflows while it is computed raises `DataError` instead.

## ModelDoesNotExist

```python
ModelDoesNotExist(model_cls: type, pk: Any)
```

Bases: `FerroError`, `LookupError`

No row matched the primary key.

`Model.get` raises it when no row has the key, and `save` on a saved instance raises it when its row is gone (deleted, or its primary key changed before saving). It is also a `LookupError`. Use `get_or_none` to get `None` instead.

Examples:

```python
from ferro import ModelDoesNotExist

try:
    await Author.get(99)
except ModelDoesNotExist as error:
    assert (error.model, error.pk) == (Author, 99)
else:
    raise AssertionError("expected ModelDoesNotExist")
```

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `model` | `type` | The model class that was looked up. |
| `pk` | `Any` | The primary key that matched no row. |

### model

```python
model: type = model_cls
```

The model class that was looked up.

### pk

```python
pk: Any = pk
```

The primary key that matched no row.

## InstanceNotLoaded

```python
InstanceNotLoaded(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `FerroError`

An unloaded instance was asked for more than its primary key.

A forward relation nothing loaded reads as an unloaded instance of its model, holding only its primary key. Reading another column, assigning one, `save()`, `model_dump()` and `model_dump_json()` raise this error, whose message names the fix: load the relation with `include()` on the query, or call `.load()` on the instance. It is not an `AttributeError`, so `hasattr()` and `getattr()` with a default raise it too, and a Pydantic model built `from_attributes` never mistakes the missing column for an absent one. See [Loaded relations](<https://ferro-orm.x54.sh/guide/queries/#loading-relations-with-include>).

Serializing the instance any other way, nested in another model, through a `TypeAdapter` or as a response model, raises Pydantic's `PydanticSerializationError` instead, with this error's message inside it; in Python mode this error is its `__cause__`. See [The unloaded instance](<https://ferro-orm.x54.sh/concepts/identity-map/#the-unloaded-instance>).

Examples:

```python
from ferro import InstanceNotLoaded

async with engines.session():  # a session that holds no author yet
    post = await Post.get(1)
    try:
        post.author.name
    except InstanceNotLoaded as error:
        assert "await post.author.load()" in str(error)
    else:
        raise AssertionError("expected InstanceNotLoaded")

    author = await post.author.load()
    assert author.name == "Ada Lovelace"
```

## SettingsError

```python
SettingsError(message: str, *, driver_message: str | None = None, sqlstate: str | None = None, constraint: str | None = None)
```

Bases: `FerroError`

The project configuration is missing, malformed, or contradicts itself.

Every message names the fix: the key to add or move, the line to write, both paths found, or the variable to set.
