# Errors

Every class is exported by `db2kit`. `instanceof` recognizes an error whatever copy of db2kit threw it: a CommonJS application also loads the ES module copy through its configuration file, and an error of one is an instance of the same class of the other ([installation.md](installation.md#configure), One configuration, two module systems).

| Class                            | When                                                                                                                                                                              | Useful fields                                                                                                                                                                                                                                    |
| :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Db2ConfigError`                 | At startup, invalid configuration. With `connectionFromEnv`, also when a connection opens while one of its variables is missing or invalid                                        | `problems`: list of every problem                                                                                                                                                                                                                |
| `Db2UsageError`                  | Misuse, before any network call: among others, `db.call` given a descriptor alone ([procedures.md](procedures.md#a-call-without-its-outcome-rule)), `unchecked()` given no reason | `code`: `INDEX_GUARD` (the index guard refused a read or a write on a large table), `USAGE` (any other misuse), `INVALID_INPUT` (`Db2InputError`). A `message` that says what to change and never holds a value of the application: log it as is |
| `Db2InputError`                  | `db.call` input values refused before any network call (type, length, null, decimals, input codec). A `Db2UsageError`                                                             | `code` (`INVALID_INPUT`), `procedure`, `issues` (every refused value, never the value)                                                                                                                                                           |
| `Db2PoolTimeoutError`            | No connection after `pool.acquireTimeoutMs`                                                                                                                                       | `code` (`POOL_TIMEOUT`), `timeoutMs`, `pool` (used, free, pending, opening)                                                                                                                                                                      |
| `Db2UnavailableError`            | Db2 counts as unreachable: `pool.breakerThreshold` connection attempts failed on the network in a row, and the next attempt is not due. No login was tried                        | `code` (`UNAVAILABLE`), `since`, `failures`, `retryAt`, `cause` (the last open error)                                                                                                                                                            |
| `Db2MaxRowsError`                | Result larger than `maxRows`                                                                                                                                                      | `maxRows`, `sql`, `tag`                                                                                                                                                                                                                          |
| `Db2QueryError`                  | Error returned by Db2                                                                                                                                                             | `code`, `sqlcode`, `sqlstate`, `sql`, `fingerprint`, `tag`, `hint` (what db2kit adds, never a value), `cause`. `messageWithoutDb2Text(error)`: the message without the text of Db2, for a log ([audit.md](audit.md#the-text-of-a-db2-error))     |
| `Db2ProcedureRejectedError`      | The outcome rule recognized a rejection: Db2 reported success, the OUT parameters say no                                                                                          | `procedure`, `reasons` and `warnings` (per field), `status`                                                                                                                                                                                      |
| `Db2ProcedureStatusUnknownError` | The procedure ran but its outcome is unknown: status not recognized, rule that threw, output unreadable                                                                           | `procedure`, `status`, `cause`                                                                                                                                                                                                                   |
| `Db2TransactionRolledBackError`  | `db.$transaction` rolled back although its callback did not throw: an error inside it was caught (`failed`), or it lasted more than `timeoutMs` (`timeout`)                       | `reason`, `cause` (the first error)                                                                                                                                                                                                              |
| `Db2TransactionCommitError`      | `COMMIT` failed: whether Db2 committed is unknown                                                                                                                                 | `cause`                                                                                                                                                                                                                                          |

## Procedure inputs

`Db2InputError` lists every refused input value of a call in `issues`: the property, the catalog name and type of the parameter, and the reason, never the value, which can be personal data. Map it to HTTP 400, with the issues as the details of the response. It extends `Db2UsageError`: test for `Db2InputError` first.

## Procedure outcomes

`Db2ProcedureRejectedError` is a business answer: map it to a 4xx response. Its message names the rejected fields only, the reasons stay in `error.reasons`, because a reason can contain an identifier. A reason is a text written by `evaluate`, or the parts of a field found by a field status (`{ code, message... }`), or a list of them. `error.warnings` holds the fields with a non-blocking problem, in the same form ([procedures.md](procedures.md#status-per-field)).

`Db2ProcedureStatusUnknownError` is always a failure, never a success by default. For a procedure that modifies data, outside a transaction, whatever it changed is already committed: check its effect before retrying, a blind retry can apply the operation twice. When the message says the outcome rule is a draft, write the rule (see [procedures.md](procedures.md#outcome-rules)).

```ts
import { Db2ProcedureRejectedError } from 'db2kit';

try {
  await db.call(myProcWithOutcome, input);
} catch (error) {
  if (error instanceof Db2ProcedureRejectedError) {
    throw new UnprocessableEntityException({ fields: error.reasons });
  }
  throw error;
}
```

## Transactions

Inside `db.$transaction`, the first error makes the transaction rollback-only. When the callback throws, `$transaction` rethrows that error after the rollback. When the callback caught it, `$transaction` throws `Db2TransactionRolledBackError` with the first error as `cause`: map the cause, not the wrapper. `Db2TransactionCommitError` means the outcome is unknown: check the effect before retrying. See [transactions.md](transactions.md).

## `Db2PoolTimeoutError`: two causes

| `pool.opening` | Cause                                                                                                                                                                                                                                                                   | What to do                                                                                                                                                                                           |
| :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| above 0        | A new connection was still being opened: the login takes longer than `pool.acquireTimeoutMs`, or the server does not answer. When the message says that neither the server nor the driver answered within `pool.connectTimeoutMs`, the network path is the likely cause | Check network access (VPN, firewall), host, port, SSL. Test the port with `Test-NetConnection <host> -Port <port>` (Windows) or `nc -vz <host> <port>`. Run `npx db2kit doctor` for the driver error |
| 0              | Every connection was busy                                                                                                                                                                                                                                               | Look for a slow query or a connection never released (`statsSink`, `acquireMs` in the audit)                                                                                                         |

## `Db2QueryError` codes

Test `error.code` rather than the SQLCODE: the code is stable and readable.

| `code`                  | SQLCODE                                                           | Meaning                                                                                                                                                                                                                                                                                                                                                                                                    | What to do                                                                                                                                                                                                                                                                                                                                                           |
| :---------------------- | :---------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DUPLICATE_KEY`         | -803                                                              | Unique key already present                                                                                                                                                                                                                                                                                                                                                                                 | Business conflict, often a 409                                                                                                                                                                                                                                                                                                                                       |
| `FOREIGN_KEY`           | -530, -531, -532                                                  | Referential constraint violated                                                                                                                                                                                                                                                                                                                                                                            | Check that the parent exists                                                                                                                                                                                                                                                                                                                                         |
| `DEADLOCK_OR_TIMEOUT`   | -911, -913                                                        | Deadlock or lock wait timeout. With -911, Db2 rolled back the whole unit of work                                                                                                                                                                                                                                                                                                                           | Retry only when the operation is idempotent                                                                                                                                                                                                                                                                                                                          |
| `RESOURCE_UNAVAILABLE`  | -904                                                              | Resource unavailable (table space stopped...)                                                                                                                                                                                                                                                                                                                                                              | Check with the DBA                                                                                                                                                                                                                                                                                                                                                   |
| `RESOURCE_LIMIT`        | -905                                                              | CPU limit reached (RLF)                                                                                                                                                                                                                                                                                                                                                                                    | Query too expensive: optimize it                                                                                                                                                                                                                                                                                                                                     |
| `UNDEFINED_OBJECT`      | -204, -206                                                        | Unknown table, view or column                                                                                                                                                                                                                                                                                                                                                                              | Check the name and the schema                                                                                                                                                                                                                                                                                                                                        |
| `SQL_SYNTAX`            | -104, -199, any SQLSTATE 42601                                    | Syntax error                                                                                                                                                                                                                                                                                                                                                                                               | Fix the SQL                                                                                                                                                                                                                                                                                                                                                          |
| `ROUTINE_NOT_FOUND`     | -440                                                              | Procedure not found with this number of parameters                                                                                                                                                                                                                                                                                                                                                         | Check schema, name and number of `?`                                                                                                                                                                                                                                                                                                                                 |
| `ROUTINE_FAILED`        | -471                                                              | The procedure failed on the z/OS side                                                                                                                                                                                                                                                                                                                                                                      | Reason code in the message, check with the mainframe team                                                                                                                                                                                                                                                                                                            |
| `NOT_AUTHORIZED`        | -551                                                              | Missing privilege                                                                                                                                                                                                                                                                                                                                                                                          | Ask the DBA for the `GRANT`                                                                                                                                                                                                                                                                                                                                          |
| `CANCELLED`             | -952                                                              | Query interrupted                                                                                                                                                                                                                                                                                                                                                                                          |                                                                                                                                                                                                                                                                                                                                                                      |
| `CONNECTION_LOST`       | -30081, SQLSTATE 08xxx                                            | Connection lost                                                                                                                                                                                                                                                                                                                                                                                            | The connection is discarded automatically, the next one is fresh                                                                                                                                                                                                                                                                                                     |
| `AUTHENTICATION_FAILED` | -30082 (SQLSTATE 08001)                                           | Login refused: user, password, expired password or revoked user                                                                                                                                                                                                                                                                                                                                            | Never retry. The pool tries no new login with the same settings (see [configuration.md](configuration.md#protection-of-the-account)): fix the credentials, then change the variables read by `connectionFromEnv` (one new attempt) or restart                                                                                                                        |
| `NULL_NOT_ALLOWED`      | -407                                                              | NULL sent to a column or parameter declared NOT NULL (observed on Db2 13 for z/OS)                                                                                                                                                                                                                                                                                                                         | A missing input, often a 400                                                                                                                                                                                                                                                                                                                                         |
| `COMPATIBILITY_LEVEL`   | -4743                                                             | SQL newer than the application compatibility level (APPLCOMPAT) of the package                                                                                                                                                                                                                                                                                                                             | Rewrite with older syntax, for instance no `OFFSET`. The message says so                                                                                                                                                                                                                                                                                             |
| `INVALID_DATETIME`      | -180, -181                                                        | A text converted to a `DATE`, `TIME` or `TIMESTAMP` is not in a form Db2 reads (-180), or not a date or time that exists (-181). Db2 names neither the value nor the parameter                                                                                                                                                                                                                             | db2kit checks every value of a `DATE`, `TIME` or `TIMESTAMP` parameter or column before sending ([procedures.md](procedures.md#checked-before-any-network-call)): this one is a text Db2 converted itself, a `CHAR` parameter the procedure converts, a text in the SQL of a query, or a value in the data. The NestJS filter answers 500: its cause can be the data |
| `VALUE_TOO_LONG`        | SQLSTATE 22001: -99999 from the driver, -302, -404, -433 from Db2 | A text longer than the column or parameter it is compared with or written to. ibm_db gives each marker the type and length of its column, so the driver refuses a longer text itself, with SQLCODE -99999 (observed on Db2 13 for z/OS). The object API refuses it before sending, with the property and the lengths. In SQL written by hand, check the length first or `CAST` the marker to a longer type |
| `OTHER`                 | others                                                            |                                                                                                                                                                                                                                                                                                                                                                                                            | Read `sqlcode` and `message`                                                                                                                                                                                                                                                                                                                                         |

## Example

```ts
import { Db2QueryError } from 'db2kit';

try {
  await db.execute(sql`INSERT INTO MYSCHEMA.TRACKING (ID, STATE) VALUES (${id}, ${'C'})`);
} catch (error) {
  if (error instanceof Db2QueryError && error.code === 'DUPLICATE_KEY') {
    throw new ConflictException(`Tracking ${id} already exists`);
  }
  throw error;
}
```
