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>
|
||||
<Select v-model="form.marketing_id" :disabled="isMarketingUser">
|
||||
<SelectTrigger id="marketing" class="w-full">
|
||||
<SelectValue placeholder="Pilih marketing (opsional)" />
|
||||
<SelectValue placeholder="Pilih marketing" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="none">
|
||||
— Tidak ada —
|
||||
</SelectItem>
|
||||
<SelectItem v-for="marketing in marketings" :key="marketing.value"
|
||||
:value="String(marketing.value)">
|
||||
{{ marketing.label }}
|
||||
|
||||
@ -19,17 +19,32 @@ export async function apiFetch<T>(url: string, options: RequestInit = {}): Promi
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
const isJson = contentType.includes('application/json');
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({})) as {
|
||||
message?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
};
|
||||
if (isJson) {
|
||||
const error = (await response.json().catch(() => ({}))) as {
|
||||
message?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
};
|
||||
|
||||
const firstValidationError = error.errors
|
||||
? Object.values(error.errors).flat()[0]
|
||||
: undefined;
|
||||
const firstValidationError = error.errors
|
||||
? Object.values(error.errors).flat()[0]
|
||||
: 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>;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user