N
Nuxt2w ago
nkmnz

Where to handle 404 in useAsyncData?

Hey folks, I have a simple composable that uses fetch to get some authorized data:
export async function useApiFetch(request, opts) {
const apiToken = useCookie('api_cookie')

try {
return await $fetch(request, {
method: 'GET',
baseURL: useRuntimeConfig().public.apiURL,
headers: {
Authorization: apiToken.value || '',
},
})
} catch (error) {
console.log('error in useApiFetch:', error)
return { data: null, error }
}
}
export async function useApiFetch(request, opts) {
const apiToken = useCookie('api_cookie')

try {
return await $fetch(request, {
method: 'GET',
baseURL: useRuntimeConfig().public.apiURL,
headers: {
Authorization: apiToken.value || '',
},
})
} catch (error) {
console.log('error in useApiFetch:', error)
return { data: null, error }
}
}
I use it in useAsyncData like this:
const { data: jobData, error } = await useAsyncData(
'jobData',
() => useApiFetch(`/jobs/${jobId}`)
)
const { data: jobData, error } = await useAsyncData(
'jobData',
() => useApiFetch(`/jobs/${jobId}`)
)
Sometimes, the job requested is no longer available, so the api returns a 404 not found. Unfortunately, this leads to nuxt throwing a 500 error during SSR and there is no way for me to catch that error – no matter how many try{}catch(e){} I wrap around - the $fetch request inside useApiFetch - the useAsyncData call - the useApiFetch inside of the useAsyncData I always get this:
ERROR [nuxt] [request error] [unhandled] [500] internal server error
ERROR internal server error
ERROR [nuxt] [request error] [unhandled] [500] internal server error
ERROR internal server error
I'm out of my depth here, any help would be greatly appreaciated 🙏🏻
3 Replies
kapa.ai
kapa.ai2w ago
Hi @nkmnz. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To handle 404 errors in useAsyncData when using a custom fetch function, you can modify your approach based on the information provided in the knowledge sources. Here's how you can address this issue: 1. First, modify your useStrapiFetch function to throw the error instead of returning it:
export async function useStrapiFetch(request, opts) {
const apiToken = useCookie('api_cookie')

try {
return await $fetch(request, {
method: 'GET',
baseURL: useRuntimeConfig().public.apiURL,
headers: {
Authorization: apiToken.value || '',
},
})
} catch (error) {
console.log('error in useApiFetch:', error)
throw error // Throw the error instead of returning it
}
}
export async function useStrapiFetch(request, opts) {
const apiToken = useCookie('api_cookie')

try {
return await $fetch(request, {
method: 'GET',
baseURL: useRuntimeConfig().public.apiURL,
headers: {
Authorization: apiToken.value || '',
},
})
} catch (error) {
console.log('error in useApiFetch:', error)
throw error // Throw the error instead of returning it
}
}
2. Then, use createError to handle the 404 error in your useAsyncData call:
const { data: jobData, error } = await useAsyncData(
'jobData',
async () => {
try {
return await useStrapiFetch(`/jobs/${jobId}`)
} catch (error) {
if (error.response?.status === 404) {
throw createError({ statusCode: 404, statusMessage: 'Job not found' })
}
throw error // Re-throw other errors
}
}
)
const { data: jobData, error } = await useAsyncData(
'jobData',
async () => {
try {
return await useStrapiFetch(`/jobs/${jobId}`)
} catch (error) {
if (error.response?.status === 404) {
throw createError({ statusCode: 404, statusMessage: 'Job not found' })
}
throw error // Re-throw other errors
}
}
)
This approach uses the createError utility, which is designed to handle errors in Nuxt 3, including 404 errors Docs > Getting-started > Error Handling > Error Page > useError Part 1 (https://nuxt.com/docs/getting-started/error-handling#useerror). By throwing a createError with a 404 status code, Nuxt will handle it appropriately during SSR without causing a 500 internal server error. This will trigger Nuxt's error handling mechanism, allowing you to display a custom error page or handle the error as needed. Additionally, you can use the useError composable to access the error in your component or page:
const error = useError()
if (error.value) {
// Handle the error, e.g., display a message to the user
}
const error = useError()
if (error.value) {
// Handle the error, e.g., display a message to the user
}
Remember that createError is meant to be thrown, and it will trigger a full-screen error page on the server-side, which you can clear with clearError if needed Docs > Getting-started > Error Handling > Error Page > useError Part 1 (https://nuxt.com/docs/getting-started/error-handling#useerror). This approach should help you handle 404 errors gracefully in your Nuxt 3 application when using useAsyncData with a custom fetch function. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@545617569206501391> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
nkmnz
nkmnzOP2w ago
@kapa.ai Ok, got it. Now it works, but how and when is the error that can be destructured from useAsyncData relevant?
Want results from more Discord servers?
Add your server