Added Error Toasts Fix #52
This commit is contained in:
@@ -1,31 +1,86 @@
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
const config = useRuntimeConfig()
|
||||
const toast = useToast()
|
||||
|
||||
const api = $fetch.create({
|
||||
baseURL: config.public.apiBase,
|
||||
credentials: "include",
|
||||
async onRequest({options}) {
|
||||
// Token aus Cookie holen
|
||||
let token: string | null | undefined = ""
|
||||
|
||||
token = useCookie("token").value
|
||||
async onRequest({ options }) {
|
||||
const token = useCookie("token").value
|
||||
|
||||
|
||||
|
||||
// Falls im Request explizit ein anderer JWT übergeben wird → diesen verwenden
|
||||
if (options.context && (options.context as any).jwt) {
|
||||
token = (options.context as any).jwt
|
||||
}
|
||||
|
||||
if (token) {
|
||||
// Falls im Request explizit ein anderer JWT übergeben wird
|
||||
if (options.context?.jwt) {
|
||||
options.headers = {
|
||||
...options.headers,
|
||||
Authorization: `Bearer ${options.context.jwt}`,
|
||||
}
|
||||
} else if (token) {
|
||||
options.headers = {
|
||||
...options.headers,
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async onRequestError({error}) {
|
||||
toast.add({
|
||||
title: "Fehler",
|
||||
description: "Eine Anfrage konnte nicht ausgeführt werden.",
|
||||
color: 'red',
|
||||
icon: 'i-heroicons-exclamation-triangle-20-solid',
|
||||
timeout: 5000 // Bleibt 5 Sekunden sichtbar
|
||||
})
|
||||
},
|
||||
|
||||
async onResponseError({ response }) {
|
||||
// Toasts nur im Client anzeigen
|
||||
console.log(response)
|
||||
if (!process.client) return
|
||||
|
||||
const status = response.status
|
||||
let title = "Fehler"
|
||||
let description = "Ein unerwarteter Fehler ist aufgetreten."
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
title = "Anfrage fehlerhaft"
|
||||
description = "Die Daten konnten nicht korrekt verarbeitet werden."
|
||||
break
|
||||
case 401:
|
||||
title = "Nicht angemeldet"
|
||||
description = "Deine Sitzung ist abgelaufen oder ungültig."
|
||||
// Optional: useCookie('token').value = null
|
||||
break
|
||||
case 403:
|
||||
title = "Zugriff verweigert"
|
||||
description = "Du hast keine Berechtigung für diesen Bereich."
|
||||
break
|
||||
case 404:
|
||||
title = "Nicht gefunden"
|
||||
description = "Die gesuchte Ressource wurde nicht gefunden."
|
||||
break
|
||||
case 500:
|
||||
title = "Server-Fehler"
|
||||
description = "Internes Problem. Bitte versuche es später erneut."
|
||||
break
|
||||
}
|
||||
|
||||
// Nuxt UI Toast Notification
|
||||
toast.add({
|
||||
title: title,
|
||||
description: description,
|
||||
color: 'red',
|
||||
icon: 'i-heroicons-exclamation-triangle-20-solid',
|
||||
timeout: 5000 // Bleibt 5 Sekunden sichtbar
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return { provide: { api } }
|
||||
return {
|
||||
provide: {
|
||||
api
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user