---
title: "Handle errors"
description: "Read a refusal's code with getBackendError, show the right sentence or the way out, and refuse from your own functions with the same codes."
canonical_url: "https://nuxt-backend.dev/docs/build/data/read-write/errors"
---
# Handle errors

> Read a refusal's code with getBackendError, show the right sentence or the way out, and refuse from your own functions with the same codes.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/strips)
- [API reference](https://nuxt-backend.dev/docs/reference/api/functions)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/errors.ts)

When a package function refuses a call (signed out, out of credits, rate limited), it throws a
`ConvexError` with a stable code: `{ code: 'insufficient_credits', balance: 0, need: 1 }`. Convex
sends that data to the client in production as well. A plain `Error` arrives there as "Server
Error", whatever its message said. The [Errors](https://nuxt-backend.dev/docs/reference/backend/errors) reference lists
every code and its fields. The package adds the stable codes, `getBackendError` to read them anywhere, and `backendError` to throw them from your own functions.

## Where a failure shows up

<table>
<thead>
  <tr>
    <th>
      You call
    </th>
    
    <th>
      A failure
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      A data composable of the package: <code>
        useSearch
      </code>
      
      , <code>
        useWorkflowStatus
      </code>
      
      , <code>
        useEmailStatus
      </code>
      
       and the others
    </td>
    
    <td>
      Lands in its <code>
        error
      </code>
      
      , already read: <code>
        { code, data, message }
      </code>
      
      . A read never throws (<a href="https://nuxt-backend.dev/docs/reference/nuxt/conventions">
        Composable conventions
      </a>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      An action of a package composable (<code>
        useBilling().checkout()
      </code>
      
      , <code>
        useWorkspace().invite()
      </code>
      
      )
    </td>
    
    <td>
      Rejects: catch it and read it with <code>
        getBackendError
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        useMutation
      </code>
      
      , <code>
        useAction
      </code>
    </td>
    
    <td>
      Rejects, the same way
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        useAsyncQuery
      </code>
      
      , <code>
        useQuery_experimental
      </code>
    </td>
    
    <td>
      Lands in the result's <code>
        error
      </code>
      
      , as the thrown error: read it with <code>
        getBackendError
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        useQuery
      </code>
      
      , <code>
        usePaginatedQuery
      </code>
    </td>
    
    <td>
      Throws during render: wrap the part that reads it in an error boundary, or use one of the forms above
    </td>
  </tr>
</tbody>
</table>

## Read a refusal

`getBackendError(error)` is auto-imported. It returns `{ code, data, message }` for a refusal and
`null` for anything else, such as a crash or an error of your own:

```vue
<script setup lang="ts">
import { api } from '#backend/api'

const transform = useAction(api.ai.transform)
const notice = ref<string | null>(null)
const outOfCredits = ref(false)

async function run(text: string) {
  notice.value = null
  try {
    await transform({ text })
  }
  catch (error) {
    const refusal = getBackendError(error)
    outOfCredits.value = refusal?.code === 'insufficient_credits'
    notice.value = refusal?.message ?? 'Something went wrong. Try again.'
  }
}
</script>
```

`message` is the sentence to show: the throw site's own sentence for the person when it wrote one
(an app's `canSignIn` refusal, say), else the code's English label. The data is typed by code, so
after `refusal.code === 'rate_limited'` you can read `refusal.data.retryAfter`, the wait in
milliseconds. Every field may be absent on this side, so check the one you use: the reader keeps
only what fits the catalog.

It reads the same codes from every source:

- a package function's refusal, and one you throw with `backendError`;
- the rate limiter's own error, from any limit called with `throws: true`, as `rate_limited` with
the limit's name;
- an auth client result (`{ data, error }`) or its `error`: the package's auth refusals carry the
same codes, and Better Auth's own 401, 403 and 429 map to `unauthenticated`, `forbidden` and
`rate_limited`. A banned account's refusal reads as `forbidden` with reason `banned`, the same
reason the package's own ban checks give, and Better Auth's 400s for a wrong or expired code,
an invalid address and a taken workspace slug read as `invalid_input` on `otp`, `email` or
`slug`;
- any of these as an `Error`'s `cause`, which is how the rejections of the auth composables
(`useLoginFlow()`, `useWorkspace()`, `usePasskeys()`, `useSessions()`) pass them on.

`useAiStream()` keeps the refusal of its last `start` in `error`, and its `status` ends in
`'error'`.

## Branch on the code

<table>
<thead>
  <tr>
    <th>
      Code
    </th>
    
    <th>
      What to offer
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        unauthenticated
      </code>
    </td>
    
    <td>
      Sign in, then retry. On a sign-in form it can also be refused credentials: show the message.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        reauthentication_required
      </code>
    </td>
    
    <td>
      A fresh sign-in, then the same call: <code>
        useReauthentication().withReauthentication(() => call())
      </code>
      
       does both.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        no_workspace
      </code>
    </td>
    
    <td>
      Choose or create a workspace.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        insufficient_credits
      </code>
    </td>
    
    <td>
      A credit pack or a bigger plan. <code>
        data.need
      </code>
      
       and <code>
        data.balance
      </code>
      
      , when present, say how far off it is.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        feature_required
      </code>
    </td>
    
    <td>
      The plans in <code>
        data.plans
      </code>
      
      , which include <code>
        data.feature
      </code>
      
      : <code>
        <UpgradePrompt :plans="refusal.data.plans" />
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        quota_exceeded
      </code>
    </td>
    
    <td>
      The plans in <code>
        data.plans
      </code>
      
      , which allow more of <code>
        data.quota
      </code>
      
       than <code>
        data.limit
      </code>
      
      ; <code>
        data.used
      </code>
      
       says how many there are.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rate_limited
      </code>
    </td>
    
    <td>
      A countdown from <code>
        data.retryAfter
      </code>
      
      , when present.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
    </td>
    
    <td>
      The message. <code>
        data.reason
      </code>
      
       says why, <code>
        banned
      </code>
      
       or <code>
        role
      </code>
      
       for example.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        invalid_input
      </code>
    </td>
    
    <td>
      The message beside the input <code>
        data.field
      </code>
      
       names.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        not_ready
      </code>
    </td>
    
    <td>
      No retry: the first purchase (<code>
        no_customer
      </code>
      
      ) or a credit pack (<code>
        not_synced
      </code>
      
      ) is what changes it.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        unavailable
      </code>
    </td>
    
    <td>
      A retry later for <code>
        provider_refused
      </code>
      
      . The other reasons need the deployment fixed; the log says what.
    </td>
  </tr>
</tbody>
</table>

## Refuse from your own functions

`backendError(code, data?, detail?)` from `nuxt-backend/functions` builds the error. The data is
checked against the code's fields, and `detail` is the English the deployment log shows:

```ts [backend/strips.ts]
import { backendError } from 'nuxt-backend/functions'
import { v } from 'convex/values'
import { workspace } from './functions'

export const rename = workspace.mutation({
  args: { id: v.id('strips'), title: v.string() },
  handler: async (ctx, { id, title }) => {
    const strip = await ctx.db.get('strips', id)
    if (strip?.workspaceId !== ctx.workspace.id) {
      throw backendError('forbidden', { reason: 'other_workspace' })
    }
    if (!title.trim()) {
      throw backendError('invalid_input', { field: 'title', message: 'Give the strip a title.' })
    }
    await ctx.db.patch('strips', id, { title: title.trim() })
  },
})
```

The `authed`, `workspace` and `admin` builders from `createFunctions` already throw `unauthenticated`,
`no_workspace` and `forbidden`. A limit of your own refuses as `rate_limited` when you call it with
`throws: true`, but the limiter throws only when it knows the wait. Keep the result, and refuse
yourself when it says no:

```ts
const { ok, retryAfter } = await rateLimiter.limit(ctx, 'sendMessage', { key: ctx.user.id, throws: true })
if (!ok) throw backendError('rate_limited', { limit: 'sendMessage', retryAfter: retryAfter || undefined })
```

In an auth hook, throw the auth library's `APIError` with the code and its fields in the body, and
the client reads it the same way:

```ts
import { APIError } from 'nuxt-backend/auth'

throw new APIError('BAD_REQUEST', { code: 'invalid_input', field: 'email', message: 'Invite a company address.' })
```

## Test it

```ts [backend/strips.test.ts]
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('a blank title is refused on its field', async () => {
  const author = await asUser(testApp())
  const id = await author.mutation(api.strips.create, { title: 'Monday' })
  await expect(author.mutation(api.strips.rename, { id, title: ' ' }))
    .rejects.toMatchObject({ data: { code: 'invalid_input', field: 'title' } })
})
```

## Related

- [Errors](https://nuxt-backend.dev/docs/reference/backend/errors): every code, its fields, label and status.
- [Function builders](https://nuxt-backend.dev/docs/build/auth/access/functions): the tiers that refuse for you.
- [Rate limits](https://nuxt-backend.dev/docs/ship/security/rate-limits): the package's limits and what a person sees.
- [Metered actions](https://nuxt-backend.dev/docs/build/ai/metered-actions): the refusals before a spend.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
