At the end of the previous lesson, Colmena Bookings' interface already moved with intent, but it still had one piece inherited from the earliest lessons: to confirm the cancellation of a booking, DashboardBookingsView calls window.confirm, a browser dialog that does not follow the application's design, cannot be animated, looks different in every browser and blocks JavaScript execution while it is open. Since Slots we have been promising our own BaseModal, and to build it we need the dialog to be rendered above everything else, even if it is declared by a component deep down in the tree: that is what <Teleport> does. This lesson also brings together two other tools related to what happens "off the normal path" of rendering: <Suspense>, which coordinates components that need to wait for asynchronous data before rendering, and the error handling mechanisms of Vue, Vue Router and the browser. In Colmena you will build BaseModal.vue and use it to replace window.confirm, turn the dashboard's profile into an async view inside a <Suspense>, create an error boundary component, ErrorBoundary.vue, and centralise all error logging in src/utils/errors.js, picking up the app.config.errorHandler you wrote in 01-04.

Contents

  1. The problem with modals: z-index, overflow and stacking contexts
  2. <Teleport>
  3. Colmena: BaseModal.vue
  4. Colmena: our own dialog instead of window.confirm
  5. <Suspense>: waiting for async components
  6. <Suspense> with RouterView, KeepAlive and Transition
  7. Colmena: the profile as an async view
  8. Error handling: the complete map
  9. onErrorCaptured: capturing descendants' errors
  10. Colmena: ErrorBoundary.vue
  11. Colmena: centralised logging in src/utils/errors.js
  12. router.onError: failures loading code after a deployment
  13. Unhandled promises
  14. Messages for the user
  15. What each mechanism captures
  16. Try it

  1. The problem with modals: z-index, overflow and stacking contexts

A modal dialog must cover the whole window, above any other content. With CSS it looks simple:

.modal {
  position: fixed;
  inset: 0;      /* top, right, bottom and left set to 0: the whole window */
  z-index: 1000;
}

But if the modal is rendered inside the component that uses it (for example, inside a row of "My bookings"), its position in the DOM can break all three properties:

Ancestor's situation Effect on the modal
overflow: hidden (or auto) It can clip the modal's content if that content does not escape with position: fixed (for example, an absolute dropdown menu)
z-index with position, opacity below 1, filter... It creates a stacking context: the modal's z-index: 1000 only competes with its siblings inside that context, and the modal may end up below the header
transform (also filter or will-change: transform) The ancestor becomes the containing block for position: fixed descendants: the modal no longer covers the window, only that ancestor

The last case is very real in Colmena: in 09-04, <TransitionGroup> applies a transform to the booking rows while they move. A modal rendered inside a row would be trapped in it during the animation.

The robust solution is for the modal to be rendered in the DOM outside any of the application's containers, directly in <body>, even though logically it still belongs to the component that uses it (which passes it props, receives its events and provides data to it with provide).

  1. <Teleport>

<Teleport> is a built-in component that renders its content in another place in the DOM, specified with the to prop, while keeping that content in its place in the component tree:

<template>
  <button type="button" @click="isOpen = true">Open</button>

  <Teleport to="body">
    <div v-if="isOpen" class="modal">
      <p>I am in the body, but I still belong to this component</p>
      <button type="button" @click="isOpen = false">Close</button>
    </div>
  </Teleport>
</template>
flowchart LR
    subgraph Tree["Component tree (logical)"]
        A["App"] --> P["DashboardBookingsView"]
        P --> M["BaseModal"]
    end
    subgraph DOM["DOM (physical)"]
        B["body"] --> APP["div#app<br/>(header, dashboard, list...)"]
        B --> MD["div.modal<br/>(teleported)"]
    end
    M -. "is rendered in" .-> MD

What does not change when teleporting:

  • Props, events and slots work the same: the content is still in the component's template.
  • provide/inject goes through the Teleport: the content can inject what its logical ancestors provide.
  • Vue DevTools shows the content inside its component.
  • Scoped styles still apply, because they depend on an attribute on the element, not on its position.

What does change: CSS selectors that depend on the DOM hierarchy (.panel .modal) stop working, and DOM events bubble up through <body>, not through the logical containers.

2.1 <Teleport>'s props

Prop Value Use
to A CSS selector ('body', '#modals') or a DOM element The target. It must exist when the Teleport mounts
disabled Boolean If true, the content is rendered in place, as if there were no Teleport. Useful for varying according to the context (for example, a panel that is a modal on mobile and is embedded in the page on desktop)
defer (Vue 3.5+) Boolean Resolves the target after the application has finished mounting the current cycle, instead of at the moment the Teleport mounts

defer solves a specific case: the target is rendered by the application itself, later in the template. For example, if App.vue had a <div id="action-bar"> after the <main>, a view that wanted to teleport its buttons there would fail without defer, because when the view mounts the <div> does not exist yet. With <Teleport defer to="#action-bar">, Vue waits for the mounting cycle to finish and then finds it. If the target is body or an element in index.html, it is not needed.

2.2 Several Teleports to the same target

Several components can teleport content to the same target: Vue appends it in mounting order, without replacing what is already there. This is what allows two modals, or a modal and a notification, to coexist in <body>: the last one mounted ends up on top (if they have the same z-index, the one that comes later in the DOM wins).

  1. Colmena: BaseModal.vue

3.1 Requirements

An accessible modal is a good deal more than a <div> on top of the page. These are the requirements, based on the WAI-ARIA guidelines for modal dialogs:

Requirement Why How
Above everything To avoid the problems in section 1 <Teleport to="body"> and position: fixed
Opened and closed from the parent The parent decides when something is asked v-model (with defineModel, 03-03)
Free content and buttons Each dialog asks different things A default slot and a scoped #actions slot
Identified as a dialog The screen reader announces "dialog" and its title role="dialog", aria-modal="true", aria-labelledby, aria-describedby
Focus moves in on opening Keyboard users must be able to act immediately Focus the element with autofocus or the first focusable one
Focus does not leave while it is open Tab must not lead to buttons hidden behind the backdrop Focus trap: Tab and Shift+Tab wrap around inside
Focus returns on closing The user must carry on where they were Remember the element focused when opening and give the focus back to it
Close with Escape A universal convention for dialogs Listen for keydown
Close by clicking the backdrop A common convention (optional) @click on the backdrop
The page does not scroll behind Prevent the mouse wheel from moving the hidden page Locking the <body>'s scrolling
Smooth entrance and exit Consistency with the rest of the application FadeTransition (09-04)

3.2 Escape: reuse v-click-outside.esc?

In 06-02 we wrote v-click-outside, with an .esc modifier that also closes on Escape. It seems made for this, but we will not use it in the modal, for three reasons:

  1. Escape must belong to the modal alone. The directive listens for keydown on the document, just like AppHeader's user menu and the Floating Vue tooltip closing we set up in main.js (07-01). With the directive, a single press of Escape would close the modal and everything else. If we listen for keydown on the modal's own container (where the focus is, thanks to the trap) and call stopPropagation(), the event does not reach the document: the modal consumes it.
  2. "Outside" the modal is the backdrop, an element of our own. For a modal dialog there is no need to detect clicks anywhere in the document: a @click on the semi-transparent backdrop is enough. It is simpler and more explicit.
  3. The directive would consider content "outside" that is not. A Floating Vue tooltip inside the modal is in turn teleported to <body>, outside the dialog: with v-click-outside, clicking it would close the modal.

The directive is still the right tool for what it was designed for: dropdowns that close when you click anywhere else.

3.3 The component

Create src/components/base/BaseModal.vue:

<script setup>
// src/components/base/BaseModal.vue
// Accessible modal dialog: it is teleported to <body>, traps the focus, closes with
// Escape or by clicking the backdrop, locks scrolling and gives the focus back on closing.
import { watch, nextTick, onMounted, onBeforeUnmount, useTemplateRef, useId } from 'vue'
import FadeTransition from './FadeTransition.vue'

const isOpen = defineModel({ type: Boolean, default: false })

const { title, closeOnBackdrop = true, fallbackFocus = null } = defineProps({
  title: { type: String, required: true },
  closeOnBackdrop: { type: Boolean, default: true },
  // Selector of the element that receives the focus if the one that opened the dialog no longer exists
  fallbackFocus: { type: String, default: null }
})

const emit = defineEmits(['close'])

const dialog = useTemplateRef('dialog')
const titleId = useId()
const descriptionId = useId()

const FOCUSABLE = [
  'a[href]', 'button:not([disabled])', 'input:not([disabled])', 'select:not([disabled])',
  'textarea:not([disabled])', '[tabindex]:not([tabindex="-1"])'
].join(', ')

let previousFocus = null // the element that had the focus when opening

function focusableElements() {
  return [...(dialog.value?.querySelectorAll(FOCUSABLE) ?? [])]
}

async function onOpen() {
  previousFocus = document.activeElement
  document.body.classList.add('no-scroll')
  await nextTick() // the dialog is now in the DOM
  const target = dialog.value?.querySelector('[autofocus]') ?? focusableElements()[0] ?? dialog.value
  target?.focus()
}

async function onClose() {
  document.body.classList.remove('no-scroll')
  const previous = previousFocus
  previousFocus = null
  await nextTick() // let the parent finish updating its DOM
  if (previous?.isConnected) previous.focus()
  else if (fallbackFocus) document.querySelector(fallbackFocus)?.focus()
}

watch(isOpen, (value) => (value ? onOpen() : onClose()))
onMounted(() => {
  if (isOpen.value) onOpen()
})
onBeforeUnmount(() => {
  if (isOpen.value) document.body.classList.remove('no-scroll')
})

function close(reason) {
  isOpen.value = false
  emit('close', reason) // 'escape', 'backdrop' or whatever the caller specifies
}

function onKeydown(event) {
  if (event.key === 'Escape') {
    event.stopPropagation() // the Escape belongs to the modal: it does not reach the document
    close('escape')
    return
  }
  if (event.key !== 'Tab') return

  // Focus trap: Tab and Shift+Tab wrap around inside the dialog
  const focusables = focusableElements()
  if (focusables.length === 0) {
    event.preventDefault()
    return
  }
  const first = focusables[0]
  const last = focusables.at(-1)
  const active = document.activeElement
  if (event.shiftKey && (active === first || active === dialog.value)) {
    event.preventDefault()
    last.focus()
  } else if (!event.shiftKey && active === last) {
    event.preventDefault()
    first.focus()
  }
}
</script>

<template>
  <Teleport to="body">
    <FadeTransition>
      <div v-if="isOpen" class="modal" @keydown="onKeydown">
        <div class="modal__backdrop" @click="closeOnBackdrop && close('backdrop')"></div>
        <div
          ref="dialog"
          class="modal__dialog"
          role="dialog"
          aria-modal="true"
          :aria-labelledby="titleId"
          :aria-describedby="descriptionId"
          tabindex="-1"
        >
          <h2 :id="titleId" class="modal__title">{{ title }}</h2>
          <div :id="descriptionId" class="modal__body">
            <slot />
          </div>
          <div v-if="$slots.actions" class="modal__actions">
            <slot name="actions" :close="close" />
          </div>
        </div>
      </div>
    </FadeTransition>
  </Teleport>
</template>

<style scoped>
.modal {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: grid;
  place-items: center;
  padding: 1rem;
}

.modal__backdrop {
  position: absolute;
  inset: 0;
  background: rgb(0 0 0 / 0.45);
}

.modal__dialog {
  position: relative; /* above the backdrop */
  width: min(28rem, 100%);
  padding: 1.5rem;
  border-radius: 0.75rem;
  background: white;
  box-shadow: 0 12px 40px rgb(0 0 0 / 0.25);
}

.modal__title {
  margin-top: 0;
}

.modal__actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1.5rem;
}
</style>

And, in src/assets/main.css, the class that locks scrolling (global, because it is applied to <body>):

/* src/assets/main.css */
body.no-scroll {
  overflow: hidden;
}

Let's go over the decisions, from top to bottom:

  • defineModel gives the parent v-model="confirmationOpen". The modal can close itself (Escape, backdrop, buttons) by assigning isOpen.value = false, and the parent finds out through the v-model.
  • useId() generates unique identifiers for aria-labelledby and aria-describedby, which connect the dialog with its title and its content: the screen reader announces "Cancel booking, dialog" and reads the question. It is the same technique as in TextField (03-05).
  • onOpen stores the focused element, locks scrolling and, after nextTick (the dialog was not yet in the DOM), first focuses an element with autofocus, if there is one; if not, the first focusable element; if there is none, the dialog itself (which is why it has tabindex="-1": focusable from code but not with Tab).
  • onClose gives the focus back after nextTick. The order matters: if the element that opened the dialog disappears as a result of the action (which is what will happen when cancelling a booking: its "Cancel" button ceases to exist), this has to be checked with the DOM already updated. isConnected says whether the element is still in the document; if not, fallbackFocus is used. Without this, the focus would fall onto <body> and the keyboard user would be sent back to the start of the page.
  • watch + onMounted: the watch reacts to changes in the model; onMounted covers the case where the modal is mounted already open. onBeforeUnmount avoids leaving <body> locked if the view unmounts with the modal open (for example, when navigating with the Back button).
  • The focus trap only steps in at the edges: if the focus is on the last element and Tab is pressed, it goes to the first; if it is on the first (or on the dialog itself) and Shift+Tab is pressed, it goes to the last. In every other case, the browser does the normal thing.
  • The #actions slot receives close, so that the parent can add a "Back" button that closes the dialog without declaring its own function.
  • <style scoped> works even though the content is in <body>: the elements carry the component's data-v-... attribute.
  • The transition is FadeTransition, which wraps the v-if element inside the Teleport: the Teleport itself is neither mounted nor unmounted, only its content.

What about HTML's <dialog> element? Current browsers have a native element, <dialog>, which with showModal() is rendered on a layer above everything else (with no need for Teleport), closes with Escape, makes the rest of the page inert and manages the focus. It is an excellent alternative and increasingly widely used. We are building the modal by hand because it is the best way to understand each requirement, and because that way we control the transition and the behaviour equally in every browser; if you choose <dialog>, the list in section 3.1 will help you check that nothing is missing.

  1. Colmena: our own dialog instead of window.confirm

4.1 DashboardBookingsView

Today, cancel(booking) starts with if (!window.confirm(question)) return (07-03). With our own dialog, the flow is split in two: one button requests the cancellation (opens the dialog) and another confirms it. In the script of src/views/dashboard/DashboardBookingsView.vue, replace the cancel function with:

// DashboardBookingsView.vue
import BaseModal from '@/components/base/BaseModal.vue'

const confirmationOpen = ref(false)
const bookingToCancel = ref(null) // the dialog's booking (kept on closing, for the animation)

function requestCancellation(booking) {
  bookingToCancel.value = booking
  confirmationOpen.value = true
}

async function confirmCancellation() {
  const booking = bookingToCancel.value
  confirmationOpen.value = false
  cancellationError.value = null
  try {
    await bookingsStore.cancelBooking(booking.id)
  } catch (error) {
    cancellationError.value = { date: booking.date, error }
  }
}

In the template, each row's button calls requestCancellation (previously cancel), the view's title gets an id and tabindex="-1" so that it can receive the focus, and the dialog is declared only once, outside the list:

<!-- DashboardBookingsView.vue -->
<h2 id="bookings-title" tabindex="-1">{{ $t('bookings.title') }}</h2>

<!-- in each row, the button (its other attributes, unchanged) -->
<BaseButton ... data-test="cancel-booking" @click="requestCancellation(booking)">

<!-- at the end of the template -->
<BaseModal
  v-model="confirmationOpen"
  :title="$t('bookings.cancelTitle')"
  fallback-focus="#bookings-title"
>
  <p v-if="bookingToCancel">
    {{ $t('bookings.confirmCancellation', {
      room: roomNameById(bookingToCancel.roomId),
      date: format.date(bookingToCancel.date)
    }) }}
  </p>
  <template #actions="{ close }">
    <BaseButton variant="secondary" autofocus @click="close('back')">
      {{ $t('bookings.keep') }}
    </BaseButton>
    <BaseButton variant="danger" data-test="confirm-cancellation" @click="confirmCancellation">
      {{ $t('bookings.yesCancel') }}
    </BaseButton>
  </template>
</BaseModal>
  • A single dialog for the whole list, not one per row: bookingToCancel indicates which booking it is about. As well as being lighter, it avoids having the modal inside a <TransitionGroup> row (although, thanks to Teleport, that would work too).
  • bookingToCancel is not emptied on closing: while the dialog fades out, it keeps showing its text. If you set it to null, the paragraph would disappear halfway through the animation.
  • autofocus on "Keep booking": faced with a destructive action, the focus starts on the safe option. An accidental Enter cancels nothing. autofocus reaches BaseButton's <button> as a fallthrough attribute, and BaseModal looks for it on opening.
  • fallback-focus: on confirming, the optimistic cancellation (05-07) changes the booking's status and its "Cancel" button disappears. The focus, which should have returned to that button, goes to the list's title.
  • Buttons with explicit text ("Keep booking", "Yes, cancel it") instead of "Cancel" and "OK": in a dialog that asks whether you want to cancel, a "Cancel" button is ambiguous.

Also delete the call to window.confirm and, if you no longer use it, the question variable.

4.2 The texts

Add to the bookings group in src/locales/en.json:

{
  "bookings": {
    "cancelTitle": "Cancel booking",
    "keep": "Keep booking",
    "yesCancel": "Yes, cancel it"
  }
}
Key es.json ca.json
bookings.cancelTitle Cancelar reserva Cancel·lar la reserva
bookings.keep Mantener la reserva Mantenir la reserva
bookings.yesCancel Sí, cancelarla Sí, cancel·la-la

The bookings.confirmCancellation key ("Cancel the booking for the {room} on {date}?") is reused as the dialog's text.

4.3 The tests

Two tests are no longer valid: those in DashboardBookingsView.spec.js (08-03) that mocked window.confirm, and the cancellation step in booking.cy.js (08-04), which relied on Cypress accepting confirm dialogs by itself.

There is a detail in the unit test: Vue Test Utils searches inside the wrapper, and the teleported content is in <body>, outside it. The simplest solution is to replace <Teleport> with a stub that renders the content in place. In mountDashboard, add to the global options:

// src/views/dashboard/__tests__/DashboardBookingsView.spec.js, in mountDashboard
global: {
  plugins: [createTestingPinia({ createSpy: vi.fn, initialState: initialState(), ...piniaOptions })],
  stubs: { teleport: true } // the modal's content is rendered inside the wrapper
}

And replace the confirmation tests:

it('asks for confirmation in a dialog and cancels on confirming', async () => {
  const { wrapper, bookingsStore } = await mountDashboard()

  await wrapper.get('.booking-list li button').trigger('click')
  const dialog = wrapper.get('[role="dialog"]')
  expect(dialog.text()).toContain('Cancel the booking for the Polen Room on Tuesday 3 November?')
  expect(bookingsStore.cancelBooking).not.toHaveBeenCalled()

  await wrapper.get('[data-test="confirm-cancellation"]').trigger('click')

  expect(bookingsStore.cancelBooking).toHaveBeenCalledWith('r-demo-1')
  expect(wrapper.find('[role="dialog"]').exists()).toBe(false)
})

it('cancels nothing if the member closes the dialog with Escape', async () => {
  const { wrapper, bookingsStore } = await mountDashboard()

  await wrapper.get('.booking-list li button').trigger('click')
  await wrapper.get('.modal').trigger('keydown', { key: 'Escape' })

  expect(wrapper.find('[role="dialog"]').exists()).toBe(false)
  expect(bookingsStore.cancelBooking).not.toHaveBeenCalled()
})

The "shows a notice if the cancellation fails" test changes in the same way: instead of mocking window.confirm, it clicks the row's button and then [data-test="confirm-cancellation"]. And vi.spyOn(window, 'confirm') is no longer needed in any of them.

In cypress/e2e/booking.cy.js, step 5 becomes:

// 5. Cancel it, confirming in the application's dialog
cy.get('@newBooking').find('[data-test="cancel-booking"]').click()
cy.get('[role="dialog"]').should('be.visible').and('contain', 'Néctar Room')
cy.get('[data-test="confirm-cancellation"]').click()
cy.get('[role="dialog"]').should('not.exist')
cy.get('@newBooking').should('contain', 'Cancelled')
cy.get('@newBooking').find('[data-test="cancel-booking"]').should('not.exist')

In Cypress nothing special is needed for the Teleport: it searches the whole document, and the dialog is in <body>.

  1. <Suspense>: waiting for async components

5.1 Async components

In 09-01 we said that an await in setup turns the component into an async one. In <script setup>, a top-level await is enough:

<script setup>
import { api } from '@/api'

// The component is not rendered until this promise resolves
const profile = await api.session.fetchProfile('[email protected]')
</script>

<template>
  <p>Member since {{ profile.memberSince }}</p>
</template>

It is convenient: profile is the data itself, with no initial null or loading state. But what does Vue render while it waits? By itself, nothing; and if the promise fails, the component never comes into existence. That is what <Suspense> is for.

A technical detail we saw in 09-01: after a top-level await in <script setup>, the compiler restores the component's context, so you can still call composables, inject and hooks after the await. In a hand-written setup() that does not happen.

5.2 <Suspense>

<Suspense> is a built-in component that waits for all the async dependencies of its content (components with an async setup and components from defineAsyncComponent), and in the meantime shows alternative content:

<Suspense>
  <!-- #default: what we want to show -->
  <DashboardProfileView />

  <!-- #fallback: what is shown while it resolves -->
  <template #fallback>
    <p>Loading your profile…</p>
  </template>
</Suspense>
Concept Detail
#default slot It must have a single root node. It can contain several async components at any depth: <Suspense> waits for all of them
#fallback slot It is shown until all the dependencies of #default have resolved
@pending event When it starts waiting
@resolve event When the content of #default is ready and is shown
@fallback event When the content of #fallback is shown
timeout prop On a second wait (the content changes to another async one), how many ms the previous content stays visible before switching to #fallback. With 0, #fallback appears immediately
suspensible prop Lets a nested <Suspense> delegate to the parent <Suspense>
Errors <Suspense> does not handle them: the error from an async setup propagates like any other (section 9)

Two behaviours that surprise people the first time:

  • After the first resolution, if the content of #default changes to another async component, <Suspense> does not show #fallback again immediately: it keeps the previous content until the new one is ready (or until the timeout passes). This avoids flickering on fast navigations.
  • Components from defineAsyncComponent are "suspensible" by default: inside a <Suspense>, their loadingComponent, errorComponent, delay and timeout options are ignored, because it is <Suspense> that controls the wait. If BuildingMap (03-06) ended up inside a <Suspense>, its MapLoading would no longer be seen, unless you added suspensible: false to its options.

5.3 A warning: it is experimental

<Suspense> has been marked as experimental in the official documentation since Vue 3.0: it works and is stable in practice (Nuxt uses it on every page), but its API could change. This has a practical consequence when choosing:

A composable that returns refs (useRequest, 09-01) An async component with <Suspense>
The component's code Must handle null, loading and error Receives the data already resolved
Who decides what is shown while loading The component itself The ancestor that has the <Suspense>
Several loads at once Each with its own state A single loading state for all of them
Reloading (a change of parameter, a retry) Natural: reload() or the reactive source The component has to be remounted
API stability Stable Experimental

In Colmena, the rule will be: useRequest and the stores for normal data loading, and <Suspense> where it adds something clear, such as an area with several sub-screens that share the same loading indicator.

  1. <Suspense> with RouterView, KeepAlive and Transition

When the four are combined, the nesting order recommended by the Vue documentation is this:

<RouterView v-slot="{ Component }">
  <template v-if="Component">
    <Transition mode="out-in">
      <KeepAlive>
        <Suspense>
          <!-- the main content -->
          <component :is="Component" />

          <!-- the loading state -->
          <template #fallback>Loading…</template>
        </Suspense>
      </KeepAlive>
    </Transition>
  </template>
</RouterView>
  • <Transition> on the outside: it animates the whole change of screen.
  • <KeepAlive> inside it: it keeps the visited screens in the cache (03-06); when you come back, they are not loaded again.
  • <Suspense> as close to the component as possible: it waits for its async dependencies.
  • v-if="Component": it avoids rendering the structure when there is no component yet (for example, while a lazy view is being downloaded on the first navigation).

You do not have to use all four layers: remove the ones you do not need, keeping the order of the ones that remain.

  1. Colmena: the profile as an async view

7.1 The profile API

The dashboard's profile currently shows only the session's data. We will add data that has to be requested from the server: the joining date and the company. In src/api/session.js:

// src/api/session.js: add (import wait, randomDelay and failSometimes from ./simulation.js)
const PROFILES = {
  '[email protected]': { memberSince: '2025-03-01', company: null },
  '[email protected]': { memberSince: '2024-09-15', company: 'Coworking Colmena' }
}

export async function fetchProfile(email, { signal } = {}) {
  await wait(randomDelay(), signal)
  failSometimes()
  const profile = PROFILES[email]
  if (!profile) {
    throw errorWithStatus(`No profile exists for "${email}"`, 404, 'profileNotFound', { email })
  }
  return structuredClone(profile)
}

7.2 An async DashboardProfileView

In src/views/dashboard/DashboardProfileView.vue, add the request with await to the script:

<script setup>
import { api } from '@/api'
import { useSessionStore } from '@/stores/session.js'

const session = useSessionStore()

// planDescriptions, unchanged

// A top-level await: the view is async and the wait is handled by a <Suspense>
const profile = await api.session.fetchProfile(session.email)
</script>

And in the template's details list, after the role:

<dt>Member since</dt>
<dd>{{ $format.date(profile.memberSince) }}</dd>
<template v-if="profile.company">
  <dt>Company</dt>
  <dd>{{ profile.company }}</dd>
</template>

profile is an ordinary, non-reactive object: it does not change while the view is mounted. If the member signs out, they leave the dashboard (the route requires a session) and the view unmounts.

7.3 DashboardView with <Suspense>

DashboardView (04-04) renders the side menu, the breadcrumbs and a <RouterView> for the sub-screens. Replace that <RouterView /> with:

<!-- DashboardView.vue -->
<RouterView v-slot="{ Component }">
  <Suspense :timeout="200">
    <component :is="Component" />
    <template #fallback>
      <p class="loading" role="status">{{ $t('app.loading') }}</p>
    </template>
  </Suspense>
</RouterView>

And add "loading": "Loading…" to the app group in en.json (in Spanish, "Cargando…"; in Catalan, "Carregant…").

  • The synchronous sub-screens notice nothing: DashboardBookingsView and DashboardInvoicesView have no async dependencies, so <Suspense> resolves straight away.
  • :timeout="200": when going from "My bookings" to "Profile", the list stays visible for 200 ms; if the profile takes longer, "Loading…" appears. That way, fast responses do not cause flickering.
  • role="status": the screen reader announces the loading without moving the focus.

And what if fetchProfile fails (remember the simulation's 10% failure rate)? The await throws, the view's setup fails and... the error travels up the component tree to app.config.errorHandler, which only writes it to the console. The user sees the dashboard with an empty gap. It is time to study error handling.

  1. Error handling: the complete map

In a Vue application, an error can occur in many places, and each place has its own mechanism:

flowchart TB
    E["An error occurs"] --> Q{"Where?"}
    Q -->|"In an operation you expect might fail<br/>(request, validation)"| T["Local try/catch<br/>→ error state and message"]
    Q -->|"In a component:<br/>setup, render, hooks,<br/>watchers, handlers"| C["It goes up through the ancestors:<br/>each one's onErrorCaptured"]
    C -->|"one of them returns false"| D["It stops: handled"]
    C -->|"nobody stops it"| H["app.config.errorHandler"]
    Q -->|"In a navigation:<br/>guard, loading a lazy view"| R["router.onError"]
    Q -->|"In a promise without a catch<br/>outside Vue"| U["unhandledrejection event"]

The first branch is the one you have been using since module 5: expected errors (the API does not respond, the room is taken) are handled where they occur, stored in the state (roomsStore.error, useRequest's error, bookingError in BookingView) and shown translated. This lesson is about the other branches: unexpected errors, or ones that slip through, which have to be contained (so that a broken part does not leave the screen blank) and logged (so that the team finds out about them).

  1. onErrorCaptured: capturing descendants' errors

onErrorCaptured(handler) registers a function on a component that is called when a descendant produces an error:

import { onErrorCaptured } from 'vue'

onErrorCaptured((error, instance, info) => {
  // error: the error thrown
  // instance: the component where it occurred
  // info: where, e.g. 'setup function', 'render function', 'mounted hook', 'v-on handler'
  console.log('A descendant has failed:', info)
  return false // stops the propagation
})

The propagation rules:

Rule Detail
Which errors arrive Those from descendants: setup (async too), rendering, lifecycle hooks, watchers, template event handlers (including rejected promises they return), directive and transition hooks
Which errors do not arrive Those of the component itself; those from code outside Vue (a setTimeout, a promise that nobody returns)
Order From the bottom up: first the closest ancestor, then the next... and finally app.config.errorHandler
return false Stops the propagation: neither the following ancestors nor app.config.errorHandler receive it
Without return false The error keeps going up and still reaches app.config.errorHandler
If the handler itself throws an error That error and the original go to app.config.errorHandler

What onErrorCaptured does not do is "repair" the broken component: if the error occurred while rendering, that component still cannot render. What the ancestor can do is stop showing it and render something else in its place. That is the error boundary pattern.

  1. Colmena: ErrorBoundary.vue

An error boundary is a component that wraps an area of the interface and, if something inside fails, shows a message and an option to retry instead of the broken content. The rest of the application (the header, the side menu) keeps working.

Create src/components/ErrorBoundary.vue:

<script setup>
// src/components/ErrorBoundary.vue
// Contains the errors of its content: it shows a notice with "Try again" instead of
// the broken content, logs the error and does not let it travel any further up.
import { ref, watch, onErrorCaptured } from 'vue'
import BaseButton from './base/BaseButton.vue'
import { translateError } from '@/i18n.js'
import { logError } from '@/utils/errors.js'

const { resetKey = null } = defineProps({
  // When it changes (e.g. the route), the error is forgotten and it tries again
  resetKey: { type: [String, Number], default: null }
})

const error = ref(null)
const attempt = ref(0)

onErrorCaptured((e, instance, info) => {
  error.value = e
  logError(e, { source: 'error-boundary', info })
  return false // handled here: it does not go further up or reach app.config.errorHandler
})

function retry() {
  error.value = null
  attempt.value++ // a new key recreates the content from scratch
}

watch(
  () => resetKey,
  () => {
    error.value = null
  }
)
</script>

<template>
  <div v-if="error" class="error-boundary notice" role="alert">
    <p>{{ translateError(error) }}</p>
    <BaseButton @click="retry">
      <template #icon>↻</template>
      {{ $t('errors.retry') }}
    </BaseButton>
  </div>
  <slot v-else :key="attempt" />
</template>
  • return false stops the propagation. That is why the boundary itself logs the error with logError (section 11): otherwise, the error would not reach app.config.errorHandler and nobody would find out.
  • translateError(error) (07-03): if the error comes from the API (code: 'connection'), the user reads "Could not connect to the Colmena server."; if it is a programming error without a code, the generic message "An unexpected error has occurred. Please try again.". Never a technical message.
  • <slot :key="attempt">: on retrying, the key changes and Vue recreates the content from scratch, instead of trying to update components that were left half-built. With an async view, that means repeating the setup and, therefore, the request.
  • resetKey: if the user navigates to another sub-screen, the previous one's error no longer makes sense.

Add the errors.retry key to the language files: "Try again", "Reintentar" and "Torna-ho a provar". Also add errors.api.profileNotFound: "Your profile could not be found.", "No se ha encontrado tu perfil." and "No s'ha trobat el teu perfil.".

10.1 The boundary in DashboardView

In DashboardView.vue, wrap the <Suspense> from section 7.3:

<!-- DashboardView.vue -->
<RouterView v-slot="{ Component, route }">
  <ErrorBoundary :reset-key="route.fullPath">
    <Suspense :timeout="200">
      <component :is="Component" />
      <template #fallback>
        <p class="loading" role="status">{{ $t('app.loading') }}</p>
      </template>
    </Suspense>
  </ErrorBoundary>
</RouterView>
// DashboardView.vue
import ErrorBoundary from '@/components/ErrorBoundary.vue'

Now, if fetchProfile fails, the error from the async setup travels up to ErrorBoundary, which shows the translated notice with "Try again" in the content area, while the side menu and the breadcrumbs are still there. When "Try again" is clicked, the view is recreated, <Suspense> waits again and, if the request succeeds, the profile appears.

Why is the boundary outside the <Suspense>? Because onErrorCaptured only captures errors from descendants. If it were inside, next to the view, it would not wrap the component that fails.

  1. Colmena: centralised logging in src/utils/errors.js

11.1 The errorHandler from 01-04

In 01-04 you wrote in main.js:

app.config.errorHandler = (error, instance, info) => {
  console.error('[Colmena Bookings] Unhandled error:', error, '| Source:', info)
}

And we announced that in a real application it would send the errors to an external service. Now there are three more sources of errors (the error boundary, the router, promises) and each one needs the same thing: to give the error a shape, add context and send it. We will centralise this in a module.

11.2 The module

Create src/utils/errors.js:

// src/utils/errors.js
// Centralised error logging: in development, to the console; in production,
// to the monitoring service. It installs the application's global handlers.

// FICTITIOUS: in a real project, this is where the SDK of a service
// such as Sentry, Bugsnag or Datadog would be initialised, and send() would call its API.
const monitoringService = {
  send(event) {
    console.info('[monitoring] Event sent:', event)
  }
}

export function logError(error, context = {}) {
  const event = {
    message: error?.message ?? String(error),
    name: error?.name ?? null,
    code: error?.code ?? null,
    status: error?.status ?? null,
    stack: error?.stack ?? null,
    route: window.location.pathname,
    timestamp: new Date().toISOString(),
    ...context
  }

  if (import.meta.env.DEV) {
    console.error(`[Colmena Bookings] Error (${context.source ?? 'unknown'}):`, error, context)
  } else {
    monitoringService.send(event)
  }
  return event
}

// A lazy view that no longer exists on the server (see section 12)
export function isCodeLoadFailure(error) {
  return /Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i
    .test(error?.message ?? '')
}

const RELOAD_KEY = 'colmena-reload-after-deployment'

export function installErrorHandling(app, router) {
  // 1. Component errors that nobody has stopped with onErrorCaptured
  app.config.errorHandler = (error, instance, info) => {
    logError(error, {
      source: 'vue',
      info,
      component: instance?.$options.name ?? instance?.$options.__name ?? null
    })
  }

  // 2. Navigation errors (guards, loading lazy views)
  router.onError((error, destination) => {
    if (isCodeLoadFailure(error) && !sessionStorage.getItem(RELOAD_KEY)) {
      sessionStorage.setItem(RELOAD_KEY, '1')
      window.location.assign(destination.fullPath) // a full load with the new code
      return
    }
    logError(error, { source: 'router', destination: destination.fullPath })
  })
  router.afterEach((to, from, failure) => {
    if (!failure) sessionStorage.removeItem(RELOAD_KEY)
  })

  // 3. Rejected promises that nobody has handled, anywhere
  window.addEventListener('unhandledrejection', (event) => {
    if (event.reason?.name === 'AbortError') return // cancellations: they are not failures
    logError(event.reason, { source: 'promise' })
  })
}

The decisions:

  • logError is the only function that knows where errors go. If the service changes tomorrow, it is changed here.
  • The event includes what the team needs to reproduce the failure: the message, the stack, the API's code and status (if it has them), the route the user was on and the moment. It does not include personal data (the email address, the content of the bookings): a monitoring service is a third party, and the GDPR applies to error logs too.
  • In development, the console, with the original error (so that the browser shows the stack with the source files); in production, sending it.
  • The service is fictitious: it writes to the console with console.info. With Sentry, for example, you would install its SDK for Vue, initialise it with the application and the router, and send would call its capture function. Many of these SDKs install their own errorHandler; in that case, installErrorHandling must run afterwards and also call the previous handler, or the SDK will stop receiving the errors.
  • component: instance.$options.__name is the name the compiler gives <script setup> components, based on the file name.

11.3 main.js

In src/main.js, replace the errorHandler block with the installation:

// src/main.js
import { installErrorHandling } from './utils/errors.js'

const app = createApp(App)

// 1. Application configuration
installErrorHandling(app, router)
app.provide(CONFIG_KEY, { centreName: 'Coworking Colmena', openingHour: 8, closingHour: 20 })

// ... the rest, unchanged

It is installed first, so that any error while installing the plugins or mounting is already logged. router is already imported at the top of main.js; registering router.onError before app.use(router) is fine, because the router exists from the moment it is created in src/router/index.js.

  1. router.onError: failures loading code after a deployment

router.onError(handler) receives the errors that occur during a navigation: a guard that throws an error, or a lazy view (() => import('@/views/RoomsView.vue')) that cannot be downloaded.

The second case has a very specific cause, which you will see as soon as you publish Colmena (10-02):

sequenceDiagram
    participant U as User
    participant N as Browser
    participant S as Server
    U->>N: Opens Colmena at 10:00
    N->>S: index.html and main-a1b2.js (version 1)
    Note over S: 11:00: version 2 is deployed.<br/>The files have new names:<br/>RoomsView-c3d4.js replaces RoomsView-9f8e.js
    U->>N: 11:30: clicks "Rooms"
    N->>S: RoomsView-9f8e.js (the name version 1 knows)
    S-->>N: 404: it no longer exists
    N-->>U: The navigation fails

When building for production, Vite gives each file a name with a hash of its content (10-01), and a new deployment replaces the old files. Anyone who had the application open is still running the previous version in memory, which requests chunks that no longer exist. The solution in installErrorHandling:

  • Detect that the error is a code-loading failure (the message varies by browser; the regular expression covers Chrome, Firefox and Safari).
  • Reload the full page at the destination address (window.location.assign): the browser downloads the new index.html, which points to the new files, and the user arrives where they wanted to go.
  • Avoid a loop: if the failure persists after reloading (the server is down; it is not a deployment), the flag in sessionStorage prevents another reload, and the error is logged. The flag is cleared after the next successful navigation.

Vite also offers its own event, vite:preloadError, which is emitted on window when any dynamic import it manages fails (not only those of the routes: also defineAsyncComponent or the lazy loading of languages from 07-03). You can listen for it with window.addEventListener('vite:preloadError', ...) to apply the same strategy; we will come back to it when we discuss building in 10-01.

  1. Unhandled promises

Some errors never go through Vue. For example, in HomeView we call roomsStore.loadRooms() without await: if that action threw an error (it does not: it is designed never to reject, 05-06), nobody would catch it. Or a setTimeout that makes a request. When a promise is rejected and nobody has a .catch, the browser emits the unhandledrejection event on window, and installErrorHandling logs it.

  • Cancellations are ignored: an AbortError is the expected result of cancelling a request (09-01), not a failure.
  • Its equivalent for synchronous errors outside Vue is window's error event. Monitoring services usually listen for both automatically.
  • It is no substitute for handling errors: it is the last safety net, for finding out about the ones that slip through. If an error shows up here, the fix is to add the missing try/catch or .catch in the right place.

  1. Messages for the user

Logging the error is for the team; the user needs something else: to know what has happened in terms they understand and what they can do. In Colmena, all roads lead to translateError:

Situation What the user sees Where
An expected API error in an action (creating or cancelling a booking) The translated message for its code, next to the action BookingView, DashboardBookingsView
A data-loading error A translated message and "Retry" useRequest in "Invoices", stores in the views
An unexpected error inside a protected area "An unexpected error has occurred. Please try again." with "Try again" ErrorBoundary
An unexpected error outside any protected area Nothing (it is logged) app.config.errorHandler
Failure to load a view after a deployment A transparent reload router.onError

The penultimate row is a reminder: if a serious error can leave an important area blank, it deserves its own ErrorBoundary. Wrapping every component would be excessive; the sensible approach is one boundary per independent area (the dashboard's content, the room's spec sheet, the catalogue).

  1. What each mechanism captures

Mechanism Captures Does not capture Use in Colmena
Local try/catch The errors of the operation it wraps Everything else createBooking in BookingView, confirmCancellation
Error state (stores, composables) The loading failures that the action or composable catches Programming errors in components roomsStore.error, useRequest's error
onErrorCaptured Errors from descendants: setup (async too), rendering, hooks, watchers, handlers, directives, transitions Errors of the component itself; code outside Vue ErrorBoundary
app.config.errorHandler Any component error that no onErrorCaptured has stopped Errors outside components (setTimeout, modules), promises not returned to Vue, navigation installErrorHandling
router.onError Errors in guards and when loading the routes' views Errors inside a view that is already mounted Reloading after a deployment, logging
unhandledrejection Rejected promises without a .catch, anywhere Synchronous errors Logging (ignoring AbortError)
window's error event Uncaught synchronous errors outside Vue Promises Covered by monitoring services
<Suspense> Nothing: it only handles the wait Errors (it lets them travel up) Combined with ErrorBoundary in DashboardView

  1. Try it

  1. The modal. As Laura, open "My bookings" and click "Cancel" on a booking: the dialog fades in, with the focus on "Keep booking". Inspect the DOM: the dialog is a direct child of <body>, outside #app. In Vue DevTools, on the other hand, it appears inside DashboardBookingsView.
  2. Keyboard. With the dialog open, press Tab several times: the focus moves from one button to the other without leaving the dialog. Press Shift+Tab from the first one: it goes to the last. Press Escape: the dialog closes and the focus returns to the row's "Cancel" button. Check that the user menu, if you had it open, has not been closed by that Escape.
  3. Backdrop and scrolling. Open the dialog, try to scroll the page with the wheel (it does not move) and click on the dark backdrop: it closes.
  4. Confirming. Open the dialog and click "Yes, cancel it": the dialog closes, the booking becomes "Cancelled" and the focus goes to the "My bookings" title (the row's button no longer exists). Change the language and repeat: the whole dialog is translated.
  5. Suspense. Go to "My bookings" and switch to "Profile": for an instant the list is still visible; if the response takes more than 200 ms, "Loading…" appears. Then, the details with "Member since".
  6. Error boundary. Set ERROR_PROBABILITY = 1 in src/api/simulation.js and go to "Profile": instead of the profile, the notice "Could not connect to the Colmena server." appears with "Try again", and the side menu keeps working. Restore the probability and click "Try again": the profile appears. In the console, you will see the error logged with source: 'error-boundary' and info: 'setup function'.
  7. A programming error. Temporarily write {{ invoices.doesNotExist.name }} in DashboardInvoicesView's template and go to "Invoices": the ErrorBoundary shows the generic message. Remove it.
  8. Without a boundary. Do the same in the template of HomeView, which is not protected: the console shows the error with source: 'vue', logged by app.config.errorHandler. Remove it.
  9. Promises. In the browser console, run Promise.reject(new Error('test')): the log entry with source: 'promise' appears.
  10. Simulated deployment. Run npm run build and npm run preview, open the application on the home page without visiting the catalogue, and in another terminal run npm run build again after changing any text in RoomsView.vue (its file name will change). Without reloading the browser, click "Rooms": the page reloads by itself and shows the catalogue with the new text.
  11. The tests. With the changes from section 4.3, npm test and npm run test:e2e green.

Common Mistakes and Tips

  • Teleporting to a target that does not exist yet. Vue warns and renders nothing. Use body or an element in index.html, or defer if the target is rendered by the application itself.
  • Writing CSS selectors that depend on the hierarchy (.panel .modal) for teleported content. It is no longer there. Use your own classes or scoped styles.
  • Forgetting to give the focus back when closing a modal, or giving it back to an element that no longer exists. The keyboard user ends up at the start of the page.
  • Locking scrolling and not unlocking it if the component unmounts with the modal open. Do it in onBeforeUnmount too. With several modals open at once, count how many there are before unlocking (VueUse offers useScrollLock).
  • Wrapping everything in <Suspense> for convenience. It is experimental and centralises the wait: for normal data loading, the stores and useRequest are more flexible.
  • Putting onErrorCaptured on the same component that fails. It only captures errors from descendants: the boundary must wrap the area.
  • Returning false in onErrorCaptured without logging the error. You make it vanish: neither the errorHandler nor the team find out.
  • Showing users technical messages (TypeError: Cannot read properties of undefined). Translate them into something understandable with a possible action.
  • Sending personal data to the monitoring service. Check what each error's context includes.
  • Tip: while the modal is open, adding the inert attribute to the application's container (#app) makes everything behind it impossible to focus or click, for screen readers too. Since the modal is teleported outside #app, it is not affected.

Exercises

Exercise 1. Write src/components/base/__tests__/BaseModal.spec.js with three tests: on opening, the focus goes to the element with autofocus; with Tab on the last element, the focus moves to the first; on closing with Escape, the focus returns to the element that had it before and close is emitted with 'escape'. Hint: mount with attachTo: document.body (so that focus works) and stubs: { teleport: true }; and focus the button that opens the dialog by hand before clicking it, because in jsdom trigger('click') does not move the focus.

Exercise 2. BookingView also uses window.confirm in its onBeforeRouteLeave (04-06), to warn that there is a half-finished booking. Replace it with a BaseModal. Hint: the guard can return a promise that resolves to true or false when the user chooses.

Exercise 3. Write a test for ErrorBoundary that mounts a child component whose setup throws an error the first time and works the second: check that the notice is shown, that logError has been called (mock the module with vi.mock('@/utils/errors.js')) and that, when "Try again" is clicked, the child's content appears.

Solutions

Solution 1.

// src/components/base/__tests__/BaseModal.spec.js
import { describe, it, expect, afterEach } from 'vitest'
import { ref, h, defineComponent } from 'vue'
import { mount, flushPromises } from '@vue/test-utils'
import BaseModal from '../BaseModal.vue'

// A minimal parent: a button that opens the dialog and two buttons inside it
const Parent = defineComponent({
  setup() {
    const isOpen = ref(false)
    const reasons = []
    return () => [
      h('button', { class: 'open', onClick: () => (isOpen.value = true) }, 'Open'),
      h(
        BaseModal,
        {
          modelValue: isOpen.value,
          'onUpdate:modelValue': (value) => (isOpen.value = value),
          onClose: (reason) => reasons.push(reason),
          title: 'Cancel booking'
        },
        {
          default: () => h('p', 'Are you sure?'),
          actions: () => [
            h('button', { class: 'keep', autofocus: true }, 'Keep'),
            h('button', { class: 'confirm' }, 'Yes')
          ]
        }
      )
    ]
  }
})

let wrapper

async function openDialog() {
  wrapper = mount(Parent, { attachTo: document.body, global: { stubs: { teleport: true } } })
  wrapper.get('.open').element.focus() // in jsdom, clicking does not move the focus
  await wrapper.get('.open').trigger('click')
  await flushPromises()
}

afterEach(() => wrapper?.unmount())

describe('BaseModal', () => {
  it('focuses the element with autofocus on opening', async () => {
    await openDialog()
    expect(document.activeElement.className).toBe('keep')
  })

  it('traps the focus: Tab on the last element goes back to the first', async () => {
    await openDialog()
    wrapper.get('.confirm').element.focus()
    await wrapper.get('.modal').trigger('keydown', { key: 'Tab' })
    expect(document.activeElement.className).toBe('keep')
  })

  it('closes with Escape, gives the focus back and emits the reason', async () => {
    await openDialog()
    await wrapper.get('.modal').trigger('keydown', { key: 'Escape' })
    await flushPromises()

    expect(wrapper.find('[role="dialog"]').exists()).toBe(false)
    expect(document.activeElement.className).toBe('open')
    expect(wrapper.findComponent(BaseModal).emitted('close')).toEqual([['escape']])
  })
})

attachTo: document.body is necessary because an element that is not in the document cannot receive the focus. afterEach unmounts so as not to leave elements or the no-scroll class on <body> between tests. The parent is written with a render function (09-03): it is the quickest way to declare a test component with v-model and slots without a template.

Solution 2.

// BookingView.vue
import { ref } from 'vue'
import BaseModal from '@/components/base/BaseModal.vue'

const leaveWarningOpen = ref(false)
let resolveLeave = null

function askToLeave() {
  leaveWarningOpen.value = true
  return new Promise((resolve) => {
    resolveLeave = resolve
  })
}

function answerLeave(leave) {
  leaveWarningOpen.value = false
  resolveLeave?.(leave)
  resolveLeave = null
}

onBeforeRouteLeave(() => {
  if (hasUnsavedChanges()) return askToLeave()
})
<BaseModal v-model="leaveWarningOpen" title="You have a half-finished booking" @close="answerLeave(false)">
  <p>If you leave, you will lose the form's details.</p>
  <template #actions>
    <BaseButton variant="secondary" autofocus @click="answerLeave(false)">Carry on with the booking</BaseButton>
    <BaseButton variant="danger" @click="answerLeave(true)">Leave without saving</BaseButton>
  </template>
</BaseModal>

The router waits for the guard's promise to resolve: true confirms the navigation and false cancels it. @close covers Escape and clicking the backdrop, which amount to staying. (For multilingual text, use keys in the language files, as in section 4.) The beforeunload warning (reloading or closing the tab) cannot be replaced: the browser only allows its own dialog in that case.

Solution 3.

// src/components/__tests__/ErrorBoundary.spec.js
import { it, expect, vi } from 'vitest'
import { h } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { mountWithPlugins } from '@tests/mount.js'
import { logError } from '@/utils/errors.js'
import ErrorBoundary from '../ErrorBoundary.vue'

vi.mock('@/utils/errors.js')

it('shows the notice, logs the error and allows retrying', async () => {
  let attempts = 0
  const Fragile = {
    setup() {
      attempts++
      if (attempts === 1) throw new Error('test failure')
      return () => h('p', { class: 'content' }, 'Content')
    }
  }

  const wrapper = mountWithPlugins(ErrorBoundary, { slots: { default: () => h(Fragile) } })
  await flushPromises()

  expect(wrapper.get('[role="alert"]').text()).toContain('An unexpected error has occurred')
  expect(logError).toHaveBeenCalledWith(expect.any(Error), expect.objectContaining({ source: 'error-boundary' }))

  await wrapper.get('button').trigger('click')
  await flushPromises()

  expect(wrapper.find('[role="alert"]').exists()).toBe(false)
  expect(wrapper.get('.content').text()).toBe('Content')
})

mountWithPlugins (08-01) provides Vue I18n, which is needed for $t and translateError. The error without a code produces the generic message. vi.mock without a factory replaces all of the module's exports with mock functions, so the test checks the call without anything being written to the console.

Conclusion

<Teleport> renders its content in another place in the DOM (with to, disabled and, since Vue 3.5, defer) without taking it out of the component tree, which solves modals' problems with z-index, overflow and containing blocks. With it you have built BaseModal.vue, an accessible dialog with an opening v-model, slots, role="dialog" and aria-modal, initial focus, a focus trap and focus restoration, closing with an Escape consumed by the modal itself (without v-click-outside.esc, for the reasons we saw) and with the backdrop, scroll locking and the transition from 09-04, and you have used it to replace window.confirm when cancelling a booking, updating its tests. <Suspense>, still experimental, coordinates the wait for async components with its #default and #fallback slots, and is nested with RouterView, KeepAlive and Transition in a specific order; in Colmena it handles the loading of DashboardProfileView. And for errors you now have the complete map: onErrorCaptured and the ErrorBoundary component to contain the failures of an area, app.config.errorHandler, router.onError (with the reload after a deployment) and unhandledrejection centralised in src/utils/errors.js with a fictitious monitoring service, and translateError so that the user always receives an understandable message.

Everything we have built so far happens in the browser: the server sends an almost empty index.html and it is JavaScript that renders Colmena Bookings. For an internal application with a session, like this one, that is the right approach. But the coworking space also needs a public website, one that search engines can find and that appears instantly on any phone, and for that the HTML must arrive already rendered from the server. That is what we will study in Server-Side Rendering (SSR) with Nuxt.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved