Error Handling
The Nuxt Shopify module provides built-in error handling for both the Storefront and the Admin API client.
Error Configuration
By default, the module will throw an error if something within a Storefront or Admin API client request fails instead of catching and returning an errors
object.
This is done so that Nuxt can take over the error handling when using a client within Nitro or with useAsyncData.
You can customize this behavior by setting the errors.throw
option in the module config:
export default defineNuxtConfig({
shopify: {
errors: {
throw: true,
},
},
})
Setting this to false will prevent clients from throwing an error when a request fails and instead return an errors
object with the response:
<script setup lang="ts">
const id = 'invalid-id'
const { data, error } = await useAsyncStorefront(`product-${id}`, `#graphql
query GetProduct($id: ID!) {
product(id: $id) {
id
title
}
}
`, {
variables: { id },
})
if (error.value) {
// Error caught by Nuxt, immediate access through useAsyncData
console.error(error.value)
}
</script>
<script setup lang="ts">
const id = 'invalid-id'
const { data } = await useAsyncStorefront(`product-${id}`, `#graphql
query GetProduct($id: ID!) {
product(id: $id) {
id
title
}
}
`, {
variables: { id },
})
if (data.value?.errors) {
// Response contains errors when not throwing
console.error(data.value.errors)
}
</script>
Handling Errors
When errors.throw
is set to true (default), Nuxt and Nitro can handle errors automatically.
For example, when a client throws an error within a Nitro endpoint, Nitro will catch it and return an error in the response with proper details.
export default defineEventHandler(() => {
const id = 'invalid-id'
const storefront = useStorefront()
// This will throw an error that will be returned as a response with error details
// [shopify] GraphQL Error: Variable $id of type ID! was provided invalid value
return storefront.request(`#graphql
query GetProduct($id: ID!) {
product(id: $id) {
id
title
}
}
`, {
variables: { id }
})
})
The module also provides hooks to log errors or notify an external service when a client request fails:
export default defineNuxtPlugin({
setup: (nuxtApp) => {
nuxtApp.hooks.hook('storefront:client:errors', ({ errors }) => {
console.error('[shopify] storefront client received errors', errors)
})
}
})
export default defineNitroPlugin({
setup: (nitroApp) => {
nitroApp.hooks.hook('storefront:client:errors', ({ errors }) => {
console.error('[shopify] storefront client received errors', errors)
})
nitroApp.hooks.hook('admin:client:errors', ({ errors }) => {
console.error('[shopify] admin client received errors', errors)
})
}
})