N
Nuxt2mo ago
Kelevra_V

Handling status codes using $fetch and try/catch statements

TL;DR: how do you handle http status codes using $fetch. Apologies if this is a newbie question but I'm curious what the best practice is for the following scenario. The nuxt client calls the nuxt server, the nuxt server calls the separate backend. As an example, for a login, if the backend returns a 400, that means a 2FA code is required. The way I have it set up now is that the call from nuxt client to nuxt server returns a 200 with the backend response, and I read that response to determine how to handle it. I was told this is inconsistent; the nuxt server should also return a 400 and should handle that. Since a 400 is considered an exception, my code would need to look something like this:
try {
const loginResponse = await login(email, password);
if (loginResponse.statusCode === 200) {
handleLogInSuccess(loginResponse);
} else {
throw createError({ statusCode: 500, statusMessage: "Error" });
}
} catch (error) {
if (error.statusCode === 400) {
handle2FARequired();
} else if (error.statusCode === 401) {
handleInvalidCredentials();
} ... else {
handleErrorFallback();
}
}
try {
const loginResponse = await login(email, password);
if (loginResponse.statusCode === 200) {
handleLogInSuccess(loginResponse);
} else {
throw createError({ statusCode: 500, statusMessage: "Error" });
}
} catch (error) {
if (error.statusCode === 400) {
handle2FARequired();
} else if (error.statusCode === 401) {
handleInvalidCredentials();
} ... else {
handleErrorFallback();
}
}
Hoping for some feedback or discussion on whether this is the proper approach. Thanks in advance.
2 Replies
manniL
manniL2mo ago
$fetch.raw give you the things
Kelevra_V
Kelevra_V2mo ago
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.