> For the complete documentation index, see [llms.txt](https://docs.baas.sh/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.baas.sh/baas-sdk/resources/error-handling.md).

# Error handling

The typed error hierarchy and how to handle each case cleanly.

Every SDK-defined error extends `BaasError` and carries a stable `code`. You can branch on the error class with `instanceof`, or on the `code` for finer cases.

```ts
import { BaasApiError, BaasAuthError, BaasWalletError } from '@baas.sh/sdk';

try {
  await baas.auth.signInWithWallet(provider, { email: 'alice@example.com' });
} catch (err) {
  if (err instanceof BaasWalletError) {
    // the wallet connection failed or was cancelled — show a "try again" UI
  } else if (err instanceof BaasApiError) {
    // the server refused: err.code is always 'API_ERROR', the reason is in err.body.code
    const { code } = err.body as { code?: string };
    console.error('Refused by the API:', err.status, code);
  } else if (err instanceof BaasAuthError) {
    // err.code: 'CHALLENGE_FETCH_FAILED' | 'SIGNIN_FAILED'
    console.error('Sign-in failed:', err.code, err.message);
  } else {
    throw err;
  }
}
```

## Error codes

| Code                              | Class                    | Meaning                                                                                                                                                                                                                                           |
| --------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WALLET_CONNECT_REJECTED`         | `BaasWalletError`        | The wallet connection step failed or was cancelled, or the wallet exposed no account.                                                                                                                                                             |
| `CHALLENGE_FETCH_FAILED`          | `BaasAuthError`          | The auth challenge couldn't be fetched (network or timeout).                                                                                                                                                                                      |
| `SIGNIN_FAILED`                   | `BaasAuthError`          | The sign-in request failed (network or timeout); a non-2xx answer surfaces as `BaasApiError` instead.                                                                                                                                             |
| `REFRESH_FAILED`                  | `BaasAuthError`          | The access token could not be refreshed. The session is kept: retry later.                                                                                                                                                                        |
| `SESSION_EXPIRED`                 | `BaasAuthError`          | The session is over: the user must sign in again.                                                                                                                                                                                                 |
| `SIGNOUT_FAILED`                  | `BaasAuthError`          | `signOut()` was not confirmed by the server (no answer, or a refusal). The session is kept: retry.                                                                                                                                                |
| `NOT_SIGNED_IN`                   | `BaasAuthError`          | An authenticated action ran with no session. Sign in first.                                                                                                                                                                                       |
| `SESSION_CHANGED`                 | `BaasAuthError`          | The session changed during the operation. Retry with the current session.                                                                                                                                                                         |
| `SIGNUP_ATTEMPT_PENDING`          | `BaasAuthError`          | `signUpWithSmartWallet()` was called with a different email while a previous sign-up is still pending. Retry with that email, sign in with it, or call `signOut()` to abandon it.                                                                 |
| `USER_OPERATION_PENDING`          | `BaasUserOperationError` | Submission or confirmation is uncertain. Save `err.operation` and resume the wait; do not blindly submit again.                                                                                                                                   |
| `NETWORK_ERROR`                   | `BaasNetworkError`       | The request failed or timed out.                                                                                                                                                                                                                  |
| `API_ERROR`                       | `BaasApiError`           | The server refused the request. `.status` and `.body.code` say why; `.body.errors` details a `400` validation error (see [Request validation errors](#request-validation-errors)), `.level` and `.validOptions` a smart contract one (see below). |
| `INVALID_SERVER_RESPONSE`         | `BaasError`              | The server returned an invalid response.                                                                                                                                                                                                          |
| `INVALID_CONFIG`                  | `BaasError`              | Invalid client options (`url`, `requestTimeout`), `{ signer }` passed on a passkey session, or an account this SDK version does not support: update `@baas.sh/sdk`.                                                                               |
| `INVALID_ARGUMENT`                | `BaasError`              | A `number` passed to `SmartUnits()`, or an invalid `to`, `value`, `data`, address, or operation reference. Pass amounts as strings.                                                                                                               |
| `CHAIN_SELECTION_REQUIRED`        | `BaasError`              | No chain is selected. Call `baas.chains.switch()` first.                                                                                                                                                                                          |
| `UNKNOWN_CHAIN`                   | `BaasError`              | The chain is not in `baas.chains.list()`. Pick one that is.                                                                                                                                                                                       |
| `TRANSACTION_REJECTED`            | `BaasWalletError`        | The user cancelled the wallet's transaction prompt.                                                                                                                                                                                               |
| `TRANSACTION_FAILED`              | `BaasError`              | A transaction or passkey operation failed for a non-user reason. `err.cause` carries the original. See [When a transaction fails](#when-a-transaction-fails).                                                                                     |
| `SIGNATURE_REJECTED`              | `BaasWalletError`        | The user cancelled the wallet's signature prompt (`signMessage`, or the sign-in message).                                                                                                                                                         |
| `SIGNATURE_FAILED`                | `BaasError`              | A signature failed for a non-user reason. `err.cause` carries the original.                                                                                                                                                                       |
| `SIGNER_REQUIRED`                 | `BaasError`              | A wallet operation ran without `{ signer }` on an external-wallet session. Pass the provider used at sign-in.                                                                                                                                     |
| `WALLET_DISCONNECTED`             | `BaasError`              | The wallet is disconnected from the site or on another account. Ask the user to reconnect with the account they signed in with.                                                                                                                   |
| `CHAIN_SWITCH_REJECTED`           | `BaasWalletError`        | The user cancelled the wallet's network switch prompt.                                                                                                                                                                                            |
| `CHAIN_SWITCH_UNSUPPORTED`        | `BaasError`              | The wallet cannot switch networks programmatically. Ask the user to switch in the wallet.                                                                                                                                                         |
| `CHAIN_SWITCH_FAILED`             | `BaasError`              | `baas.chains.switch()` failed for another reason. `err.cause` carries the original.                                                                                                                                                               |
| `WRONG_NETWORK`                   | `BaasError`              | The operation targets a chain the session cannot use, or the wallet is on another chain. Select a supported chain with `baas.chains.switch()`; an existing operation must use its original network.                                               |
| `PASSKEY_UNAVAILABLE`             | `BaasError`              | Passkeys cannot run here: server-side code, a browser without WebAuthn, or a page not served over HTTPS (`localhost` is fine).                                                                                                                    |
| `PASSKEY_CEREMONY_NOT_COMPLETED`  | `BaasError`              | The passkey prompt did not complete: dismissed, timed out, or no matching passkey on this device. Offer to try again.                                                                                                                             |
| `OPERATION_ABORTED`               | `BaasError`              | The operation was aborted through the `signal` you passed, or a newer passkey sign-in or sign-up superseded its ceremony.                                                                                                                         |
| `PASSKEY_NOT_SYNCED`              | `BaasError`              | Sign-up refused a passkey that is not backed up across devices. Ask the user to use a synced passkey manager.                                                                                                                                     |
| `PASSKEY_IDENTITY_MISSING`        | `BaasError`              | A passkey operation ran on a session without a passkey. Sign in with `signInWithSmartWallet()` first.                                                                                                                                             |
| `SMART_WALLET_IDENTITY_REQUIRED`  | `BaasError`              | `baas.smartWallet.activate()` needs a passkey session; the current session is an external wallet, or there is none.                                                                                                                               |
| `SMART_WALLET_ACCOUNT_NOT_ACTIVE` | `BaasError`              | The passkey wallet is not activated on that chain yet. Select that chain and call `baas.smartWallet.activate()`, then retry.                                                                                                                      |

### When a transaction fails

An external-wallet send puts the revert reason in `err.message` when the transaction carries one.

A passkey send that reverted throws `BaasTransactionError`, which carries the `transactionHash`.

### When confirmation is uncertain

A timeout does not prove that a transaction failed. For a passkey send, save `err.operation`. When the user checks again, pass it unchanged to `waitForUserOperation()` without signing or submitting again:

```ts
// savedOperation is the err.operation retained by your application.
const tx = await baas.wallet.waitForUserOperation(savedOperation, {
  timeoutMs: 60_000,
});
const receipt = await tx.wait();
```

The user must be signed in and the operation's network must still be available. The resumed wait can also fail; retain the reference and show its current status. For an external-wallet transaction, keep the returned transaction hash and check its receipt on the original network before considering a new send.

## Sign-up and sign-in refusals

A refused sign-up or sign-in is a `BaasApiError`; `err.body.code` says why.

| `err.body.code`                   | HTTP | Meaning                                                   | What to do                                                     |
| --------------------------------- | ---- | --------------------------------------------------------- | -------------------------------------------------------------- |
| `email_already_in_use`            | 409  | Another account already uses this email.                  | Sign in with that account.                                     |
| `auth_email_mismatch`             | 409  | The email is not the one this account is registered with. | Sign in with the account's email.                              |
| `smart_wallet_already_registered` | 422  | The account already exists.                               | Sign in.                                                       |
| `auth_challenge_invalid_or_used`  | 409  | The sign-up attempt can no longer be completed.           | Sign in if the account may exist, otherwise start over.        |
| `passkey_not_synced`              | 422  | The passkey is not backed up across devices.              | Ask for a synced passkey.                                      |
| `webauthn_not_configured`         | 503  | The passkey domain is not set.                            | Set it in [Wallet Settings](/baas-console/wallet-settings.md). |

## Request validation errors

When the API refuses an input, a malformed email passed to `setEmail()` for instance, the SDK throws a `BaasApiError` with `.status === 400`, and `err.body.errors` lists the reasons as `{ field, message }` objects:

```ts
import { BaasApiError } from '@baas.sh/sdk';

try {
  await baas.user.setEmail(userInput);
} catch (err) {
  if (err instanceof BaasApiError && err.status === 400) {
    const { errors } = err.body as { errors?: { field: string; message: string }[] };
    showToast(errors?.[0]?.message ?? err.message);
  }
}
```

One response can carry several entries, one per broken rule; `field` is empty when the error is not tied to one field.

## Smart contract validation errors

When you call `baas.contract(...)` with an unknown class name, address, function, or argument list, BaaS returns a `BaasApiError` carrying two extra properties to help you guide users:

* `.level: 'contract' | 'address' | 'chainId' | 'function' | 'params'` — the step that failed.
* `.validOptions: readonly string[]` — what was valid at that step.

```ts
try {
  await baas.contract('ERC20x').address('0x…').function('mint').params(1000).read();
} catch (err) {
  if (err instanceof BaasApiError && err.level === 'contract') {
    console.log('Did you mean:', err.validOptions);
    // → ['ERC20', 'ERC721', 'MyToken']
  }
}
```

| `.level`     | HTTP       | Meaning                                                                                                                                           | `.validOptions`                                        |
| ------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| `'contract'` | 404        | Unknown class name                                                                                                                                | All registered class names                             |
| `'address'`  | 404        | No deployment at this address under that class                                                                                                    | Deployments for the requested class                    |
| `'chainId'`  | 400 or 404 | The chain isn't in your project (`'chain_id_not_in_catalog'`, 400), or the address isn't registered on that chain (`'deployment_not_found'`, 404) | chainIds this address is registered on                 |
| `'function'` | 400        | Function not declared in the ABI                                                                                                                  | Function names declared in the ABI                     |
| `'params'`   | 400        | Invalid or ambiguous arguments (see `err.body.code` for the subcase)                                                                              | Type-only signatures, full signatures, or helper names |

Other errors leave `.level` undefined, so `if (err.level)` tells you when suggestions are available.

Within a level, `err.body.code` tells the cases apart. At `'params'` it is `params_mismatch` (the arguments do not match; `validOptions` lists the accepted signatures), `params_ambiguous` (several overloads match; pick one with `Typed.*` or the signature, see [Disambiguating overloaded functions](/baas-sdk/blockchain/smart-contracts.md#disambiguating-overloaded-functions)), or `invalid_typed_wrapper` (an unknown `Typed.*` type; `validOptions` lists the helpers).

## Event filter errors

A mistake in an `events()` filter is a `BaasApiError` with `status` 400; `err.body.code` says which.

| `err.body.code`              | Cause                                                                                                                               |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `event_not_in_abi`           | `event` names an event the contract's ABI does not declare.                                                                         |
| `where_requires_one_event`   | An `args.<name>` rule is set without `event`, or `event` names an overloaded event. Pass one canonical signature.                   |
| `where_field_not_filterable` | A rule names a field this history does not have; the message lists the fields it has.                                               |
| `invalid_where`              | The `where` document is malformed, a value exceeds its allowed size, or an operator does not apply to its field.                    |
| `invalid_where_value`        | A rule's value has the wrong format, such as letters instead of a decimal integer string.                                           |
| `unit_binding_unavailable`   | A rule gives an amount with `SmartUnits()` on an argument no unit binds, or whose unit depends on a token id. Pass the raw integer. |
| `unit_value_invalid`         | A `SmartUnits()` amount is not a valid decimal or cannot be represented exactly at the unit's precision.                            |

## Unit errors

For native transaction `value`, an invalid `SmartUnits()` amount throws `BaasError` with `INVALID_ARGUMENT`. The server errors below concern contract arguments and filters.

When an argument wrapped with [`SmartUnits()`](/baas-sdk/blockchain/smart-units.md) can't be converted, BaaS returns a `BaasApiError` with the reason in `err.body.code`. For these errors, `.level` and `.validOptions` are `undefined`, and the `if (err.level)` check above skips them.

| `err.body.code`               | HTTP | Meaning                                                                                                                                                                                                                                                 |
| ----------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `unit_binding_unavailable`    | 400  | No unit covers that argument, or the wrapper sits inside a tuple or an array that no unit you declared binds. Pass the value in base units; a unit is declared with the next ABI version.                                                               |
| `unit_wrapper_invalid`        | 400  | The wrapper is malformed, or `SmartUnits()` was combined with a `Typed.*` marker on the same argument. To disambiguate an overload, [pin its canonical signature](/baas-sdk/blockchain/smart-contracts.md#disambiguating-overloaded-functions) instead. |
| `unit_value_invalid`          | 400  | The amount is not a valid decimal (`'1,5'`) or cannot be represented exactly at the unit's precision (`'0.1234565'` on a 6-decimal token).                                                                                                              |
| `unit_arguments_invalid`      | 400  | The decimals depend on another argument, an ERC-6909 token `id` for instance, that couldn't be read from the call.                                                                                                                                      |
| `unit_resolution_pending`     | 422  | BaaS hasn't read those decimals yet. Retry shortly.                                                                                                                                                                                                     |
| `unit_resolution_unavailable` | 422  | Those decimals can't be read, and retrying won't help. Send the amount in base units, without the wrapper.                                                                                                                                              |

A `400` means the call needs a change. A `422` is about the decimals, and only `unit_resolution_pending` is worth a retry.

## Next

* [Exported types](/baas-sdk/resources/exported-types.md) — import the error classes you use with `instanceof`.
* [API reference](/baas-sdk/resources/api-reference.md) — method signatures and which errors they can throw.
* [Troubleshooting](/baas-sdk/troubleshooting.md) — common pitfalls and how to resolve them.
