Get `statusMessage` from $fetch
export function getErrorMsg(error: unknown): string {
console.log(error instanceof Error);
console.log(typeof error === "object");
console.log(error !== null);
console.log(error.statusCode);
console.log(error.statusMessage);
console.log(error.message);
console.error(error);
if (error instanceof Error || (typeof error === "object" && error !== null)) {
if ("statusMessage" in error) {
return error.statusMessage as string;
}
if ("message" in error) {
return error.message as string;
}
}
return String(error);
}
export function getErrorMsg(error: unknown): string {
console.log(error instanceof Error);
console.log(typeof error === "object");
console.log(error !== null);
console.log(error.statusCode);
console.log(error.statusMessage);
console.log(error.message);
console.error(error);
if (error instanceof Error || (typeof error === "object" && error !== null)) {
if ("statusMessage" in error) {
return error.statusMessage as string;
}
if ("message" in error) {
return error.message as string;
}
}
return String(error);
}
statusMessage
are empty and message
== [POST] "/api/user/user-chracter/unlock": 400
.
Here is how i call it:
try
{
await $fetch("/api/user/user-chracter/unlock", {
method: "POST",
body: {
rank: hereRank,
},
});
} catch (error) {
alert("Failed to unlock: " + getErrorMsg(error));
}
try
{
await $fetch("/api/user/user-chracter/unlock", {
method: "POST",
body: {
rank: hereRank,
},
});
} catch (error) {
alert("Failed to unlock: " + getErrorMsg(error));
}
2 Replies
import { FetchError } from 'ofetch'
export function logFetchError (error: unknown, message: string) {
if (error instanceof FetchError) {
const e = error as FetchError
const status = e.response?.status ?? 'Unknown Status'
const statusText = e.response?.statusText ?? 'Unknown Status Text'
const hasMessage = e.data?.message !== undefined
console.error(`${message}: ${status} - ${statusText} ${hasMessage ? `--- ${JSON.stringify(e.data)}` : ''}`)
} else {
console.error(message)
}
}
import { FetchError } from 'ofetch'
export function logFetchError (error: unknown, message: string) {
if (error instanceof FetchError) {
const e = error as FetchError
const status = e.response?.status ?? 'Unknown Status'
const statusText = e.response?.statusText ?? 'Unknown Status Text'
const hasMessage = e.data?.message !== undefined
console.error(`${message}: ${status} - ${statusText} ${hasMessage ? `--- ${JSON.stringify(e.data)}` : ''}`)
} else {
console.error(message)
}
}
will test
works thank you ❤️