nkmnz
nkmnz
NNuxt
Created by nkmnz on 12/12/2024 in #❓・help
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 🙏🏻
6 replies