---
title: "Error"
description: "Готовый компонент ошибки с поддержкой NuxtError."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/error"
---
# Error

> Готовый компонент ошибки с поддержкой NuxtError.

## Использование

Компонент Error отрисовывает элемент `<main>`, который вместе с компонентом [SidebarLayout](https://b24-ui.bx-shef.by/raw/docs/components/sidebar-layout.md) создаёт раскладку на всю доступную высоту окна.

### Ошибка

Пропс `error` показывает сообщение об ошибке.

**Nuxt:**

> [!NOTE]
> See: https://nuxt.com/docs/guide/directory-structure/error
> Чаще всего пропс `error` приходит в файл `error.vue`.

```vue
<template>
  <B24Error :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}" />
</template>
```

> [!TIP]
> По умолчанию сообщение о статусе отрисовывается как `h1`. Чтобы изменить тег, передайте в пропс `as` объект: например, `:as="{ statusMessage: 'h2' }"`. Так же можно задать корневой элемент: `:as="{ root: 'div', statusMessage: 'h2' }"`.

### Иконка

Пропс `icon` показывает иконку над кодом статуса.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24Error :icon="RocketIcon" :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}" />
</template>
```

### Аватар

Пропс `avatar` показывает [аватар](https://b24-ui.bx-shef.by/raw/docs/components/avatar.md) над кодом статуса (используется, только если не задан `icon`).

```vue
<template>
  <B24Error :avatar="{src:'https://github.com/bitrix24.png'}" :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}" />
</template>
```

### Цвет

Пропс `color` окрашивает вложенный [аватар](https://b24-ui.bx-shef.by/raw/docs/components/avatar.md). Явно заданный `avatar.color` перекрывает это значение по умолчанию.

```vue
<template>
  <B24Error color="air-primary-alert" :avatar="{src:'https://github.com/bitrix24.png'}" :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}" />
</template>
```

Слот `#leading` показывает свой элемент, например логотип.

```vue
<template>
  <B24Error :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}">
  <template #leading>
    
<img src="https://github.com/bitrix24.png" alt="Bitrix24" class="size-10 rounded-full">

  </template>
</B24Error>
</template>
```

### Кнопка очистки

Пропс `clear` настраивает кнопку очистки или скрывает её (значение `false`).

Кнопку можно настроить любым свойством компонента [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md).

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24Error :clear="{color:'air-primary-alert',size:'xl',icon:RocketIcon,class:'rounded-full'}" :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}" />
</template>
```

### Перенаправление

Пропс `redirect` перенаправляет пользователя на другую страницу при нажатии на кнопку очистки. По умолчанию `/`.

```vue
<template>
  <B24Error redirect="/docs/getting-started/" :error="{status:404,statusText:'Страница не найдена',message:'Страницы, которую вы ищете, не существует.'}" />
</template>
```

## Примеры

### В `error.vue`

Используйте компонент Error в `error.vue`:

```vue [error.vue]
<script setup lang="ts">
import type { NuxtError } from '#app'

const props = defineProps<{
  error: NuxtError
}>()
</script>

<template>
  <B24App>
    <B24SidebarLayout :use-light-content="false">

      <B24Error :error="error" />

    </B24SidebarLayout>
  </B24App>
</template>
```

> [!TIP]
> Чтобы раскладка и возможности совпадали, можно повторить код `app.vue` в файле `error.vue`. Пример: [https://github.com/bitrix24/b24ui/blob/main/docs/app/error.vue](https://github.com/bitrix24/b24ui/blob/main/docs/app/error.vue)

> [!NOTE]
> Подробнее об обработке ошибок — в [документации Nuxt](https://nuxt.com/docs/getting-started/error-handling#error-page). При использовании `nuxt generate` рекомендуем добавить `fatal: true` в вызов `createError`, чтобы страница ошибки точно отобразилась:
> ```vue [pages/[...slug].vue]
> <script setup lang="ts">
> const route = useRoute()
> const { data: page } = await useAsyncData(route.path, () => queryContent(route.path).findOne())
> if (!page.value) {
>   throw createError({ status: 404, statusText: 'Page not found', fatal: true })
> }
> </script>
> ```

## API

### Пропсы

```ts
/**
 * Props for the Error component
 */
interface ErrorProps {
  /**
   * The element or component this component should render as.
   * @default 'main'
   */
  as?: any;
  /**
   * The icon displayed above the status code.
   */
  icon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * The avatar displayed above the status code.
   * Used only when `icon` is not set.
   */
  avatar?: AvatarProps | undefined;
  /**
   * Default `color` for the inner `B24Avatar`. A non-`undefined` `avatar.color` overrides it.
   */
  color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-warning" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-tertiary-no-accent" | "air-selection" | "air-boost" | "air-primary-no-accent";
  error?: Partial<NuxtError<unknown> & { message: string; }> | undefined;
  /**
   * The URL to redirect to when the error is cleared.
   * @default '/'
   */
  redirect?: string | undefined;
  /**
   * Display a button to clear the error in the links slot.
   * `{ size: 'lg', color: 'air-primary', label: 'Back to home' }`
   * @default true
   */
  clear?: boolean | ButtonProps | undefined;
  b24ui?: { root?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; leadingAvatar?: SlotClass; leadingAvatarSize?: SlotClass; statusCode?: SlotClass; statusMessage?: SlotClass; message?: SlotClass; links?: SlotClass; } | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the Error component
 */
interface ErrorSlots {
  default(): any;
  leading(): any;
  statusCode(): any;
  statusMessage(): any;
  message(): any;
  links(): any;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    error: {
      slots: {
        root: 'min-h-[calc(100vh-var(--topbar-height))] flex flex-col items-center justify-center text-center',
        leading: 'mb-4 flex items-center justify-center',
        leadingIcon: 'size-10 shrink-0 text-legend',
        leadingAvatar: 'shrink-0',
        leadingAvatarSize: 'lg',
        statusCode: 'text-(length:--ui-font-size-sm) font-(--ui-font-weight-semi-bold) text-legend',
        statusMessage: 'mt-2 text-(length:--ui-font-size-4xl)/(--ui-font-line-height-md) sm:text-(length:--ui-font-size-5xl)/(--ui-font-line-height-md) font-(--ui-font-weight-bold) text-label text-balance',
        message: 'mt-4 text-(length:--ui-font-size-2xl)/(--ui-font-line-height-md) text-description text-balance',
        links: 'mt-8 flex items-center justify-center gap-6'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
