fix: improve error handling in API fetch function to manage non-JSON responses and session expiration
This commit is contained in:
parent
5108490f9d
commit
91b3870f1c
@ -708,13 +708,10 @@ function submit() {
|
|||||||
<FieldLabel for="marketing">Marketing</FieldLabel>
|
<FieldLabel for="marketing">Marketing</FieldLabel>
|
||||||
<Select v-model="form.marketing_id" :disabled="isMarketingUser">
|
<Select v-model="form.marketing_id" :disabled="isMarketingUser">
|
||||||
<SelectTrigger id="marketing" class="w-full">
|
<SelectTrigger id="marketing" class="w-full">
|
||||||
<SelectValue placeholder="Pilih marketing (opsional)" />
|
<SelectValue placeholder="Pilih marketing" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectGroup>
|
<SelectGroup>
|
||||||
<SelectItem value="none">
|
|
||||||
— Tidak ada —
|
|
||||||
</SelectItem>
|
|
||||||
<SelectItem v-for="marketing in marketings" :key="marketing.value"
|
<SelectItem v-for="marketing in marketings" :key="marketing.value"
|
||||||
:value="String(marketing.value)">
|
:value="String(marketing.value)">
|
||||||
{{ marketing.label }}
|
{{ marketing.label }}
|
||||||
|
|||||||
@ -19,17 +19,32 @@ export async function apiFetch<T>(url: string, options: RequestInit = {}): Promi
|
|||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const contentType = response.headers.get('content-type') ?? '';
|
||||||
|
const isJson = contentType.includes('application/json');
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const error = await response.json().catch(() => ({})) as {
|
if (isJson) {
|
||||||
message?: string;
|
const error = (await response.json().catch(() => ({}))) as {
|
||||||
errors?: Record<string, string[]>;
|
message?: string;
|
||||||
};
|
errors?: Record<string, string[]>;
|
||||||
|
};
|
||||||
|
|
||||||
const firstValidationError = error.errors
|
const firstValidationError = error.errors
|
||||||
? Object.values(error.errors).flat()[0]
|
? Object.values(error.errors).flat()[0]
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
throw new Error(firstValidationError ?? error.message ?? 'Permintaan gagal diproses.');
|
throw new Error(firstValidationError ?? error.message ?? 'Permintaan gagal diproses.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 401 || response.status === 419) {
|
||||||
|
throw new Error('Sesi Anda telah berakhir. Silakan muat ulang halaman dan coba lagi.');
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Permintaan gagal diproses (HTTP ${response.status}).`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isJson) {
|
||||||
|
throw new Error('Server mengembalikan respons yang tidak valid. Silakan muat ulang halaman.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.json() as Promise<T>;
|
return response.json() as Promise<T>;
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user