nuxt-modules / nuxt-modules/strapi
How to handle errors when using useAsyncData?
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 717
- Forks
- 89
- Avg merge
- 7h 3m
- Merged PRs (30d)
- 6
Description
I've spent a bit of time researching error handling with useAsyncData and I've found very little on this subject. In my app I have a page which views an article list. When a user clicks an article it navigates to a single article view using the article id. I use the following code to retrieve the article:
<script setup lang="ts">
import type { Article } from '~/types'
const route = useRoute()
const { findOne } = useStrapi()
const { data: article, error } = await useAsyncData('article', () =>
findOne<Article>('articles', +route.params.id, {
populate: { hero: true },
}))
</script>
If I try to retrieve an invalid article using the API direct with http://localhost:1337/api/articles/2 I receive a 404 and a response:
{
"data": null,
"error": {
"status": 404,
"name": "NotFoundError",
"message": "Not Found",
"details": {}
}
}
But when I inspect the error object from the above code using console.log('error:', JSON.stringify(error)) I get in response:
{
"_object": {
"article": {
"message": "",
"statusCode": 500
}
},
"_key": "article",
"__v_isRef": true
}
I would expect the error object to contain the same 404. and perhaps a message Not Found. Why would I receive a 500?
Also, how should I manage an error in the template? Should I use a v-if to hide the content area or perform a redirect to articles? If I use a v-if should it be conditional on a property of the error object or on the data itself?
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the reported useAsyncData call with useStrapi().findOne and compare its error with the direct /api/articles/2 response. Trace how the 404 is propagated into the returned error ref, then verify the documented template handling for missing data or errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- nuxt, typescript
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100