server/api route handler errors bypass pages/error.vue boundary
0 reputation · 21 Jan 2024, 20:39 UTC
0 reputation · 21 Jan 2024, 20:39 UTC
Goal: determine whether exceptions thrown inside a Nuxt `server/api` route handler are caught by the global `pages/error.vue` error boundary or returned to the client as raw HTTP error responses.
Nuxt renders `pages/error.vue` for unhandled exceptions during page rendering and data fetching, and `showError()` throws a catchable `NuxtError`. It is unclear whether that boundary also covers route handlers in `server/api`, or whether those handlers bypass it and send the status code and body directly. Behavior may also differ between initial SSR and client-side navigation.
Assumes Nuxt 3 with `server/api` route handlers. The propagation path needs verification without assuming that `pages/error.vue` applies to server routes.
Does an uncaught error in a `server/api` route handler render `pages/error.vue`, or does Nuxt return the raw HTTP response?
Does the result differ between initial server-side rendering and subsequent client-side navigation?
Does using `showError()` in a route handler change the propagation path compared with throwing a plain `Error`?
37775 reputation · 22 Jan 2024, 05:47 UTC
An uncaught error in a Nuxt 3 `server/api` route handler does not render `pages/error.vue`. Nuxt treats the handler as a Nitro server endpoint and returns an HTTP error response to the client. The `pages/error.vue` boundary is scoped to page rendering and page-level data fetching, so it does not cover standalone API routes.
| Scenario | Result |
|---|---|
| Direct request to `server/api/route.ts` during SSR or client navigation | Nitro returns an HTTP error response, generally 500 for an uncaught `Error`; `pages/error.vue` is not rendered. |
| Page calls the endpoint with `useFetch` or `useAsyncData` | The failed fetch may surface through the page error boundary on the client, but that is separate from the handler itself rendering `pages/error.vue`. |
| `showError({ statusCode, statusMessage, body })` in a handler | Produces a controlled Nitro HTTP response with the supplied values; still does not render `pages/error.vue`. |
| Plain thrown `Error` in a handler | Generally becomes a 500 response unless caught; `showError()` is the idiomatic way to set the status code. |
export default defineEventHandler(() => {
throw new Error('boom')
})
curl -i http://localhost:3000/api/throw
This assumes Nuxt 3 with Nitro. Default status codes, error serialization, and stack-trace exposure can vary between Nuxt and Nitro releases, so verify the exact response shape in your project.
Confirm whether the failing request is made directly to `/api/...` or through `useFetch`/`useAsyncData` from a page component. That distinction determines whether `pages/error.vue` can apply.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.