Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle errors when using useAsyncData? #392

Open
nad-au opened this issue Feb 21, 2024 · 2 comments
Open

How to handle errors when using useAsyncData? #392

nad-au opened this issue Feb 21, 2024 · 2 comments
Labels
question Further information is requested

Comments

@nad-au
Copy link

nad-au commented Feb 21, 2024

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?

@nad-au nad-au added the question Further information is requested label Feb 21, 2024
@re-ovo
Copy link

re-ovo commented Jul 18, 2024

Same problem, did you solve it?

@N-index
Copy link

N-index commented Aug 15, 2024

Same question. I tried wrapping findOne with try ... catch, but failed to catch the raw error of strapi.
So I found out the strapiClient source code, it does not throw strapi raw error but passes the error to strapi:error hook.
We can only get the raw error in strapi:error hook, maybe we should detect if data is null inside page then display 404, for other error then toast message in hook.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants