Where to handle 404 in useAsyncData?
Hey folks, I have a simple composable that uses fetch to get some authorized data:
I use it in
useAsyncData
like this:
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:
I'm out of my depth here, any help would be greatly appreaciated 🙏🏻3 Replies
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:
2. Then, use createError
to handle the 404 error in your useAsyncData
call:
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:
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:
----------------------<@545617569206501391> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
@kapa.ai Ok, got it. Now it works, but how and when is the error that can be destructured from
useAsyncData
relevant?