Custom useFetch
I'm refactoring my custom use fetch since the api always returns a specific type if there is an error.
How can I specify when there is an error response from the api that it is of type MyApiErrorResponse or something else?
3 Replies
Hi @LordGhandi. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To specify a custom error type (e.g., MyApiErrorResponse) for your custom useFetch composable in Nuxt, you can leverage the generic parameters of useFetch. The second generic parameter of useFetch allows you to define the error type. Here’s how you can do it:
Now, when you use your custom useAPI composable, the error ref will be typed as Ref<MyApiErrorResponse | undefined>, allowing you to safely access your custom error fields:
This approach is documented in the Nuxt guide for custom useFetch composables, including an example with a custom error type using the FetchError from ofetch, but you can substitute your own error interface as shown above. This ensures type safety and better error handling in your application Custom useFetch in Nuxt.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
<@358749735323959308> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
This still gives my a Typescript error:
I also tried to change the type of ProblemDetails in the return useFetch to FetchError<ProblemDetails>
:
It still gives the same error