Logo

dev-resources.site

for different kinds of informations.

Nuxt3 : API error handling

Published at
3/13/2024
Categories
nuxt
errors
api
nuxt3
Author
v0id-4lps
Categories
4 categories in total
nuxt
open
errors
open
api
open
nuxt3
open
Author
9 person written this
v0id-4lps
open
Nuxt3 : API error handling

Hello World

First post here, hello world!

Context

  • Nuxt 3.10.3
  • Vue 3.4.15

In Nuxt 3.10.3 you can't retrieve custom error message properly.

If you write a custom error message you cannot be able to retrieve it without a little but dirty workaround.

Example

Here is a short example :

  1. A simple API event handler throwing a basic error
  2. A simple page with 2 actions:
    • getting an error with $fetch()
    • getting an error with useFetch()
    • and displaying the result
# /pages/error.vue

<template>
    <p><button @click="onClickFetch">GetError with $fetch()</button></p>
    <p><button @click="onClickUseFetch">GetError with useFetch()</button></p>
    <pre v-if="myError">
- statusCode: {{ myError.statusCode }}
- statusMessage: {{ myError.statusMessage }}
- message: {{ myError.message }}
- data: {{ myError.data }}
    </pre>
</template>

<script setup lang="ts">
const myError = useState('myError')

const onClickFetch = async e => {
    myError.value = null;
    try {
        const data = await $fetch('/api/error')
    } catch (error) {
        myError.value = error
    }
}

const onClickUseFetch = async e => {
    myError.value = null;
    const { data, error, execute, pending, refresh, status } = await useFetch('/api/error')
    myError.value = error
}
</script>
Enter fullscreen mode Exit fullscreen mode
# /server/api/error.ts

export default defineEventHandler(async event => {
    throw createError({
        statusCode: 500,
        statusMessage: 'MyError statusMessage (éàè)',
        message: 'MyError message (éàè)'
        data: {
            data: {
                message: `MyError data message (éàè)`,
            },
        },
    })
})
Enter fullscreen mode Exit fullscreen mode

Result

- statusCode: 500
- statusMessage: Internal Server Error
- message: [GET] "/api/error": 500 Internal Server Error
- data:
{
    data: {
        message: `MyError data message (éàè)`,
    },
}
Enter fullscreen mode Exit fullscreen mode

As you can see, .statusMessage and .message are not returning your custom message.

Workaround

Dirty workaround : use .data to pass your custom error message.

# /server/api/error.ts

export default defineEventHandler(async event => {
    throw createError({
        statusCode: 500,
        statusMessage: 'Internal Server Error',
        // Here we have to define the `data` property
        data: {
            message: `My custom error message`,
        },
    })
})
Enter fullscreen mode Exit fullscreen mode
<template>
    <div v-if="myError">
        <!-- Here we have to use .data.data.message -->
        <p>{{ myError.data.data.message }}</p>
    </div>
</template>

<script setup lang="ts">
const myError = useState('myError')

try {
    const data = await $fetch('/api/error')
} catch (error) {
    myError.value = error
}
</script>
Enter fullscreen mode Exit fullscreen mode

It's dirty because your have to do 2 things :

  1. writing the data block on every error you want to throw
  2. using .data.data.message every time you want to display your message

Not found a better solution from now.

If you know a better solution, please, let us know in comment.

nuxt3 Article's
30 articles in total
Favicon
Renderización Dinámica de Componentes en Vue 3 y Nuxt 3: Guía Práctica y Caso Real
Favicon
Nuxt3 CSR Background Image Lazy loading
Favicon
DartsMash: a platform for darts enthusiasts
Favicon
Nuxt3 : limitation on Layers & Modules
Favicon
Using postgresql with nuxt3 by ORM(sequelize)
Favicon
Nuxt3 : API error handling
Favicon
Nuxt Icon
Favicon
Integrating Nuxt 3 with Recaptcha v3 for Token Handling 🤖🔐
Favicon
Nuxt 3 Starter
Favicon
Nuxt 3 Builder: A Tailored Editor for Developers
Favicon
Build an X clone w/ Nuxt UI
Favicon
Nuxt3 Form with Feedback
Favicon
Custom 404 Page in Nuxt
Favicon
Nuxt 3 authentication with pinia
Favicon
Nuxt 3, UnoCSS, and Preset rem to px
Favicon
Configuração e instalação do Nuxt 3
Favicon
The DevOnly component in Nuxt 3: A developer's best friend
Favicon
Storyblok Nuxt 3 news 🗞
Favicon
Implementing OpenID Connect (OIDC) Authentication with Nuxt 3
Favicon
Authentication in Nuxt 3
Favicon
Adding ESLint and Prettier to Nuxt 3 ✨ (2024)
Favicon
API Management in Nuxt 3 with TypeScript
Favicon
Docker and Nuxt 3
Favicon
Pinia and Nuxt 3
Favicon
Adding Pinia to Nuxt 3 🍍 (2023)
Favicon
Adding Vitest to Nuxt 3 ⚡ (2023)
Favicon
Adding Tailwind CSS to Nuxt 3 🍃 (2023)
Favicon
How I set up eslint in my projects
Favicon
How to create and minify Vuetify 3 Nuxt 3 project bundle
Favicon
Build an Intercom clone in Nuxt.js - Part Two

Featured ones: