handle failed fetch errors with popup

This commit is contained in:
Christopher Bisset 2022-07-30 15:29:56 +10:00
parent f7ea6d236e
commit 73f1314cc1
3 changed files with 25 additions and 6 deletions

View file

@ -5,6 +5,11 @@
export let ms = 3000;
let visible = false;
let timeout: number;
window.addEventListener('unhandledrejection', function (promiseRejectionEvent) {
$alertStore = promiseRejectionEvent.reason;
});
const onMessageChange = (message: string, ms: number) => {
clearTimeout(timeout);
if (!message) {
@ -12,7 +17,10 @@
visible = false;
} else {
visible = true;
if (ms > 0) timeout = window.setTimeout(() => {$alertStore = ''}, ms); // and hide it after ms milliseconds
if (ms > 0)
timeout = window.setTimeout(() => {
$alertStore = '';
}, ms); // and hide it after ms milliseconds
}
};
$: onMessageChange($alertStore, ms); // whenever the alert store or the ms props changes run onMessageChange
@ -20,7 +28,13 @@
</script>
{#if visible}
<div transition:slide class="absolute alert text-lg left-1/2 transform -translate-x-1/2 justify-center shadow-lg max-w-lg" on:click={() => {$alertStore = ''}}>
<div
transition:slide
class="absolute alert text-lg left-1/2 transform -translate-x-1/2 justify-center shadow-lg max-w-lg"
on:click={() => {
$alertStore = '';
}}
>
<p>{$alertStore}</p>
</div>
{/if}

View file

@ -163,7 +163,7 @@
});
}
export async function getDevices() {
export async function getDevices(): Promise<any> {
// variables in local storage
let headscaleURL = localStorage.getItem('headscaleURL') || '';
let headscaleAPIKey = localStorage.getItem('headscaleAPIKey') || '';
@ -177,6 +177,7 @@
let headscaleDevices = [new Device()];
let headscaleDeviceResponse: Response = new Response();
// attempt to get the user data
await fetch(headscaleURL + endpointURL, {
method: 'GET',
headers: {
@ -190,12 +191,14 @@
headscaleDeviceResponse = response;
} else {
return response.text().then((text) => {
throw JSON.parse(text).message;
apiTestStore.set('failed');
throw text;
});
}
})
.catch((error) => {
apiTestStore.set(error);
apiTestStore.set('failed');
throw error;
});
await headscaleDeviceResponse.json().then((data) => {
@ -205,7 +208,8 @@
headscaleDevices = data.machines.sort((a: Device, b: Device) => (a[sortKey as keyof Device] > b[sortKey as keyof Device] ? -1 : 1));
}
});
headscaleDeviceStore.set(headscaleDevices)
// set the store
headscaleDeviceStore.set(headscaleDevices);
}
export async function getDeviceRoutes(deviceID: string): Promise<Route> {

View file

@ -4,6 +4,7 @@
import Alert from '$lib/common/Alert.svelte';
import Stores from '$lib/common/Stores.svelte';
import { headscaleThemeStore } from '$lib/common/stores.js'
// NOTE: the element that is using one of the theme attributes must be in the DOM on mount
</script>