N
Nuxt6mo ago
Prem

`$fetch` error handling.

Hi, is this how i'm supposed call POST API call?
try {
await $fetch("/api/auth/login", {
method: "POST",
body: data
});
} catch (error) {
console.log(error?.data?.message);
}
try {
await $fetch("/api/auth/login", {
method: "POST",
body: data
});
} catch (error) {
console.log(error?.data?.message);
}
No description
2 Replies
xergic
xergic6mo ago
import { FetchError } from 'ofetch'

try {
await $fetch("/api/auth/login", {
method: "POST",
body: data
});
} catch (error) {
if (error instanceof FetchError) {
console.log(error.response?._data)
}
}
import { FetchError } from 'ofetch'

try {
await $fetch("/api/auth/login", {
method: "POST",
body: data
});
} catch (error) {
if (error instanceof FetchError) {
console.log(error.response?._data)
}
}
Ragura
Ragura6mo ago
The above is how I'm handling it now too. Made a separate function parseError to do the type checking so I wouldn't have to put the boilerplate there all the time, but this is the recommended way to handle errors in a try/catch regardless of using Nuxt or not. You should double check which fields you want from the object by inspecting the FetchError type (such as statusMessage).
Want results from more Discord servers?
Add your server