---
title: Error handling
description: Error codes keypal returns and throws, and how to handle them
---

keypal reports problems two ways:

- `verify()` returns them: `{ valid: false, error, errorCode }`. It doesn't throw for a bad key.
- Management and audit-log methods throw an `ApiKeyError`.

Errors from your storage, cache or database client (connection failures, constraint violations) are passed through unchanged, not wrapped in an `ApiKeyError`.

## ApiKeyError

```typescript
type ApiKeyError = {
  code: ApiKeyErrorCode
  message: string
  details?: unknown
}
```

It is a plain object, not an `Error` instance, so `instanceof Error` is `false` and it has no stack trace. Check `code`:

```typescript
import { ApiKeyErrorCode, type ApiKeyError } from 'keypal'

function isApiKeyError(error: unknown): error is ApiKeyError {
  return typeof error === 'object' && error !== null && 'code' in error
    && Object.values(ApiKeyErrorCode).includes((error as ApiKeyError).code)
}
```

## Error codes

`ApiKeyErrorCode` is a const object; each value equals its name, e.g. `ApiKeyErrorCode.REVOKED === "REVOKED"`.

### Returned by verify()

| Code | Message | When |
| --- | --- | --- |
| `MISSING_KEY` | Missing API key | No key in the string or headers. |
| `INVALID_FORMAT` | Invalid API key format | Wrong prefix, or longer than the maximum key length. |
| `INVALID_KEY` | Invalid API key | No stored key has this hash. |
| `REVOKED` | API key has been revoked | Revoked or rotated. |
| `EXPIRED` | API key has expired | `expiresAt` has passed or can't be parsed. |
| `DISABLED` | API key is disabled | `enabled` is `false`. |

A key in more than one state reports the first of `REVOKED`, `EXPIRED`, `DISABLED`. Details are on [Verification](/docs/api-reference/verification).

### Thrown by methods

| Code | Message | Thrown by |
| --- | --- | --- |
| `KEY_NOT_FOUND` | API key not found | `revoke`, `rotate`, `enable`, `disable` when no key has the id. |
| `ALREADY_REVOKED` | API key is already revoked | `revoke` on a revoked key. |
| `CANNOT_MODIFY_REVOKED` | Cannot modify a revoked key | `rotate`, `enable`, `disable` on a revoked key. |
| `ALREADY_ENABLED` | API key is already enabled | `enable` on an enabled key. |
| `ALREADY_DISABLED` | API key is already disabled | `disable` on a disabled key. |
| `AUDIT_LOGGING_DISABLED` | Audit logging is not enabled | Audit-log methods when `auditLogs` is not `true`. |
| `STORAGE_NOT_SUPPORTED` | Storage does not support this operation | Management methods when `storage` is a `KeyLookup`; `updateLastUsed` without `update`; audit-log methods when the storage lacks them. |

### Reserved

`STORAGE_ERROR` ("Storage error occurred") and `CACHE_ERROR` ("Cache error occurred") exist in `ApiKeyErrorCode`, but keypal doesn't currently return or throw them. You can use them in your own code with `createApiKeyError`.

## Handling verify results

```typescript
import { ApiKeyErrorCode } from 'keypal'

const result = await keys.verify(request.headers)

if (!result.valid) {
  const status = result.errorCode === ApiKeyErrorCode.MISSING_KEY
    || result.errorCode === ApiKeyErrorCode.INVALID_FORMAT
    || result.errorCode === ApiKeyErrorCode.INVALID_KEY
    ? 401
    : 403
  return Response.json({ error: result.error, code: result.errorCode }, { status })
}
```

## Handling thrown errors

```typescript
try {
  await keys.disable(keyId, { userId: adminId })
} catch (error) {
  if (!isApiKeyError(error)) throw error

  switch (error.code) {
    case ApiKeyErrorCode.KEY_NOT_FOUND:
      return Response.json({ error: error.message }, { status: 404 })
    case ApiKeyErrorCode.ALREADY_DISABLED:
      return new Response(null, { status: 204 })
    case ApiKeyErrorCode.CANNOT_MODIFY_REVOKED:
      return Response.json({ error: error.message }, { status: 409 })
    default:
      throw error
  }
}
```

## createApiKeyError()

```typescript
createApiKeyError(code: ApiKeyErrorCode, details?: unknown): ApiKeyError
```

Returns `{ code, message, details }` with the standard message for `code`. Useful in a custom storage or middleware that should fail the same way keypal does.

```typescript
throw createApiKeyError(ApiKeyErrorCode.STORAGE_NOT_SUPPORTED, { method: 'findByTags' })
```
