Kelevra_V
Kelevra_V
NNuxt
Created by Kelevra_V on 5/30/2024 in #❓・help
Handling status codes using $fetch and try/catch statements
thx for responding but after looking into it I don't believe that's it at all. Here's another example which I hope is clearer: The call from nuxt client to nuxt server:
try {
const res = await $fetch(`/api/posts/`, {
method: "GET",
});
if (res.statusCode === 200 && res.payload) {
posts.value = res.payload as Post[];
} else {
throw new Error(res.message);
}
} catch (error: Response | any) {
console.error("error", error);
}
try {
const res = await $fetch(`/api/posts/`, {
method: "GET",
});
if (res.statusCode === 200 && res.payload) {
posts.value = res.payload as Post[];
} else {
throw new Error(res.message);
}
} catch (error: Response | any) {
console.error("error", error);
}
The nuxt server then queries a separate backend which, if the post is not found, would return a 404. Should the nuxt server return a 404 as well or a 200? If for example I use throw createError on the server to return a 404, $fetch on the client would throw an exception, and I would need to handle that in the catch block of a try/catch statement. I'm just wondering if this is a good way to handle errors or if theres a better way.
3 replies