Skip to content

Modern Docker Management, Designed for Everyone

chore: cleanup try catch statements

Kyle Mendell83a90fcd7107
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index 1d5d55010..e8036bca6 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -4,7 +4,7 @@
import { openConfirmDialog } from './confirm-dialog';
import { goto, refreshAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { ArcaneButton, arcaneButtonVariants, type ArcaneButtonSize } from '#lib/components/arcane-button/index.js';
import DeploySplitButton from '#lib/components/deploy-split-button/deploy-split-button.svelte';
@@ -279,7 +279,7 @@
const removeVolumes = checkboxStates['removeVolumes'] === true;
const result = await removeMutation.mutateAsync({ removeVolumes });
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_action_failed_with_type({
action: type === 'project' ? m.compose_destroy() : m.common_remove(),
@@ -333,7 +333,7 @@
if (watch) {
enterInteractiveWatchInternal(operationStartedAt);
}
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_action_failed_with_type({ action: m.common_redeploy(), type }),
onSuccess: async (data) => {
@@ -380,25 +380,32 @@
}
try {
- await projectService.deployProject(
- id,
- 'up',
- watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {},
- options ?? deployOptionsStore.takeRequestOptions()
+ const operationResult1 = await tryCatch(
+ (async () => {
+ await projectService.deployProject(
+ id,
+ 'up',
+ watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {},
+ options ?? deployOptionsStore.takeRequestOptions()
+ );
+ if (watch) {
+ enterInteractiveWatchInternal(operationStartedAt);
+ }
+ await refreshAll();
+ itemState = 'running';
+ onActionComplete('running');
+ })()
);
- if (watch) {
- enterInteractiveWatchInternal(operationStartedAt);
- }
- await refreshAll();
- itemState = 'running';
- onActionComplete('running');
- } catch (error) {
- const message =
- error instanceof Error ? error.message : m.common_action_failed_with_type({ action: m.common_start(), type });
- if (watch) {
- operationWatchStore.fail(message);
- } else {
- toast.error(message);
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
+ const message =
+ error instanceof Error ? error.message : m.common_action_failed_with_type({ action: m.common_start(), type });
+ if (watch) {
+ operationWatchStore.fail(message);
+ } else {
+ toast.error(message);
+ }
}
} finally {
setLoading('start', false);
@@ -464,15 +471,22 @@
}
try {
- await projectService.pullProjectImages(id, watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {});
- await refreshAll();
- onActionComplete(itemState);
- } catch (error) {
- const message = error instanceof Error ? error.message : m.images_pull_failed();
- if (watch) {
- operationWatchStore.fail(message);
- } else {
- toast.error(message);
+ const operationResult2 = await tryCatch(
+ (async () => {
+ await projectService.pullProjectImages(id, watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {});
+ await refreshAll();
+ onActionComplete(itemState);
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const error = operationResult2.error;
+
+ const message = error instanceof Error ? error.message : m.images_pull_failed();
+ if (watch) {
+ operationWatchStore.fail(message);
+ } else {
+ toast.error(message);
+ }
}
} finally {
setLoading('pull', false);
@@ -483,20 +497,27 @@
setLoading('build', true);
try {
- const buildProvider = projectBuildProvider;
- await projectService.buildProjectImages(
- id,
- {
- provider: buildProvider,
- push: buildProvider === 'depot',
- load: buildProvider !== 'depot'
- },
- () => {}
+ const operationResult3 = await tryCatch(
+ (async () => {
+ const buildProvider = projectBuildProvider;
+ await projectService.buildProjectImages(
+ id,
+ {
+ provider: buildProvider,
+ push: buildProvider === 'depot',
+ load: buildProvider !== 'depot'
+ },
+ () => {}
+ );
+ await refreshAll();
+ })()
);
- await refreshAll();
- } catch (error) {
- const message = error instanceof Error ? error.message : m.build_failed();
- toast.error(message);
+ if (operationResult3.error !== null) {
+ const error = operationResult3.error;
+
+ const message = error instanceof Error ? error.message : m.build_failed();
+ toast.error(message);
+ }
} finally {
setLoading('build', false);
}
diff --git a/frontend/src/lib/components/activity/activity-cancel.ts b/frontend/src/lib/components/activity/activity-cancel.ts
index 1b5d5641e..ed78f9d1e 100644
--- a/frontend/src/lib/components/activity/activity-cancel.ts
+++ b/frontend/src/lib/components/activity/activity-cancel.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { toast } from 'svelte-sonner';
import { m } from '#lib/paraglide/messages.js';
@@ -16,10 +17,15 @@ export function confirmCancelActivity(activityId: string) {
label: m.activity_cancel_confirm(),
destructive: true,
action: async () => {
- try {
- await activityStore.cancelActivity(activityId);
- toast.success(m.activity_cancel_success());
- } catch (error) {
+ const operationResult1 = await tryCatch(
+ (async () => {
+ await activityStore.cancelActivity(activityId);
+ toast.success(m.activity_cancel_success());
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
if ((error as { response?: { status?: number } })?.response?.status === 409) {
toast.info(m.activity_cancel_already_finished());
await activityStore.refresh();
diff --git a/frontend/src/lib/components/activity/activity-center.svelte b/frontend/src/lib/components/activity/activity-center.svelte
index b8ab60c13..de584d38c 100644
--- a/frontend/src/lib/components/activity/activity-center.svelte
+++ b/frontend/src/lib/components/activity/activity-center.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { onMount } from 'svelte';
import ResponsiveDialog from '#lib/components/ui/responsive-dialog/responsive-dialog.svelte';
import * as Collapsible from '#lib/components/ui/collapsible/index.js';
@@ -44,19 +46,24 @@
label: m.activity_clear_history_confirm(),
destructive: true,
action: async () => {
- try {
- const result = await activityStore.clearHistory();
- if (result.failed.length > 0) {
- toast.warning(
- m.activity_clear_history_partial({
- count: result.succeeded,
- environments: result.failed.map((failure) => failure.environmentName).join(', ')
- })
- );
- return;
- }
- toast.success(m.activity_clear_history_success());
- } catch (error) {
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const result = await activityStore.clearHistory();
+ if (result.failed.length > 0) {
+ toast.warning(
+ m.activity_clear_history_partial({
+ count: result.succeeded,
+ environments: result.failed.map((failure) => failure.environmentName).join(', ')
+ })
+ );
+ return;
+ }
+ toast.success(m.activity_clear_history_success());
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const error = requestResult1.error;
+
console.error('Failed to clear activity history:', error);
toast.error(m.activity_clear_history_failed());
}
diff --git a/frontend/src/lib/components/auth/mfa-challenge.svelte b/frontend/src/lib/components/auth/mfa-challenge.svelte
index deeea5fa1..6e4503969 100644
--- a/frontend/src/lib/components/auth/mfa-challenge.svelte
+++ b/frontend/src/lib/components/auth/mfa-challenge.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { startAuthentication, type PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';
import { ApiKeyIcon, AlertIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -33,14 +35,21 @@
busy = true;
error = null;
try {
- const credential = await startAuthentication({
- optionsJSON: challenge.options as unknown as PublicKeyCredentialRequestOptionsJSON
- });
- const response = await passkeyService.finishMFA(challenge.transactionId, credential);
- await onComplete(response);
- } catch (value) {
- if (!isCancelledError(value)) {
- error = normalizeAuthenticationError(value, m.auth_mfa_failed()).message;
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const credential = await startAuthentication({
+ optionsJSON: challenge.options as unknown as PublicKeyCredentialRequestOptionsJSON
+ });
+ const response = await passkeyService.finishMFA(challenge.transactionId, credential);
+ await onComplete(response);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const value = operationResult1.error;
+
+ if (!isCancelledError(value)) {
+ error = normalizeAuthenticationError(value, m.auth_mfa_failed()).message;
+ }
}
} finally {
busy = false;
@@ -54,10 +63,17 @@
busy = true;
error = null;
try {
- const response = await passkeyService.finishRecovery(challenge.transactionId, recoveryCode.trim());
- await onComplete(response);
- } catch (value) {
- error = normalizeAuthenticationError(value, m.auth_mfa_failed()).message;
+ const operationResult2 = await tryCatch(
+ (async () => {
+ const response = await passkeyService.finishRecovery(challenge.transactionId, recoveryCode.trim());
+ await onComplete(response);
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const value = operationResult2.error;
+
+ error = normalizeAuthenticationError(value, m.auth_mfa_failed()).message;
+ }
} finally {
busy = false;
}
diff --git a/frontend/src/lib/components/auth/passkey-settings.svelte b/frontend/src/lib/components/auth/passkey-settings.svelte
index 4a867adf6..7d30c1ac5 100644
--- a/frontend/src/lib/components/auth/passkey-settings.svelte
+++ b/frontend/src/lib/components/auth/passkey-settings.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import {
browserSupportsWebAuthn,
startRegistration,
@@ -102,12 +104,17 @@
}
async function refreshCapabilities(): Promise<PasskeyCapabilities | null> {
- try {
- const loadedCapabilities = await passkeyService.getCapabilities();
- capabilities = loadedCapabilities;
- return loadedCapabilities;
- } catch {
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const loadedCapabilities = await passkeyService.getCapabilities();
+ capabilities = loadedCapabilities;
+ return loadedCapabilities;
+ })()
+ );
+ if (requestResult1.error !== null) {
return null;
+ } else {
+ return requestResult1.data;
}
}
@@ -144,9 +151,15 @@
const action = pendingAction;
pendingAction = null;
if (!action) return;
- try {
- await action(grant.token);
- } catch (value) {
+
+ const operationResult1 = await tryCatch(
+ (async () => {
+ await action(grant.token);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const value = operationResult1.error;
+
showPasskeyError(m.account_passkey_step_up_failed(), value, m.account_passkey_request_failed_description());
}
}
@@ -159,17 +172,24 @@
await runWithStepUp(async (stepUpToken) => {
adding = true;
try {
- const challenge = await passkeyService.beginRegistration(stepUpToken || undefined);
- const credential = await startRegistration({
- optionsJSON: challenge.options as unknown as PublicKeyCredentialCreationOptionsJSON
- });
- const created = await passkeyService.finishRegistration(challenge.ceremonyId, credential);
- passkeys = [...passkeys, created];
- toast.success(m.account_passkey_added());
- await loadAccountData();
- } catch (value) {
- if (!(value instanceof Error && value.name === 'NotAllowedError')) {
- showPasskeyError(m.account_passkey_add_failed(), value, m.account_passkey_add_failed_description());
+ const operationResult2 = await tryCatch(
+ (async () => {
+ const challenge = await passkeyService.beginRegistration(stepUpToken || undefined);
+ const credential = await startRegistration({
+ optionsJSON: challenge.options as unknown as PublicKeyCredentialCreationOptionsJSON
+ });
+ const created = await passkeyService.finishRegistration(challenge.ceremonyId, credential);
+ passkeys = [...passkeys, created];
+ toast.success(m.account_passkey_added());
+ await loadAccountData();
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const value = operationResult2.error;
+
+ if (!(value instanceof Error && value.name === 'NotAllowedError')) {
+ showPasskeyError(m.account_passkey_add_failed(), value, m.account_passkey_add_failed_description());
+ }
}
} finally {
adding = false;
@@ -193,12 +213,17 @@
return;
}
await runWithStepUp(async (stepUpToken) => {
- try {
- const updated = await passkeyService.rename(passkey.id, editingName, stepUpToken);
- passkeys = passkeys.map((item) => (item.id === updated.id ? updated : item));
- cancelRename();
- toast.success(m.account_passkey_renamed());
- } catch (value) {
+ const operationResult3 = await tryCatch(
+ (async () => {
+ const updated = await passkeyService.rename(passkey.id, editingName, stepUpToken);
+ passkeys = passkeys.map((item) => (item.id === updated.id ? updated : item));
+ cancelRename();
+ toast.success(m.account_passkey_renamed());
+ })()
+ );
+ if (operationResult3.error !== null) {
+ const value = operationResult3.error;
+
showPasskeyError(m.account_passkey_rename_failed(), value, m.account_passkey_request_failed_description());
}
});
@@ -213,12 +238,17 @@
destructive: true,
action: () => {
void runWithStepUp(async (stepUpToken) => {
- try {
- await passkeyService.deleteMine(passkey.id, stepUpToken);
- passkeys = passkeys.filter((item) => item.id !== passkey.id);
- toast.success(m.account_passkey_deleted());
- await loadAccountData();
- } catch (value) {
+ const operationResult4 = await tryCatch(
+ (async () => {
+ await passkeyService.deleteMine(passkey.id, stepUpToken);
+ passkeys = passkeys.filter((item) => item.id !== passkey.id);
+ toast.success(m.account_passkey_deleted());
+ await loadAccountData();
+ })()
+ );
+ if (operationResult4.error !== null) {
+ const value = operationResult4.error;
+
showPasskeyError(m.account_passkey_delete_failed(), value, m.account_passkey_request_failed_description());
}
});
@@ -229,12 +259,17 @@
async function enableMFA() {
await runWithStepUp(async (stepUpToken) => {
- try {
- const generated = await passkeyService.enableMFA(stepUpToken);
- recoveryCodes = generated.codes;
- toast.success(m.account_passkey_mfa_enabled());
- await loadAccountData();
- } catch (value) {
+ const operationResult5 = await tryCatch(
+ (async () => {
+ const generated = await passkeyService.enableMFA(stepUpToken);
+ recoveryCodes = generated.codes;
+ toast.success(m.account_passkey_mfa_enabled());
+ await loadAccountData();
+ })()
+ );
+ if (operationResult5.error !== null) {
+ const value = operationResult5.error;
+
showPasskeyError(m.account_passkey_mfa_enable_failed(), value, m.account_passkey_request_failed_description());
}
});
@@ -242,12 +277,17 @@
async function disableMFA() {
await runWithStepUp(async (stepUpToken) => {
- try {
- await passkeyService.disableMFA(stepUpToken);
- recoveryCodes = [];
- toast.success(m.account_passkey_mfa_disabled());
- await loadAccountData();
- } catch (value) {
+ const operationResult6 = await tryCatch(
+ (async () => {
+ await passkeyService.disableMFA(stepUpToken);
+ recoveryCodes = [];
+ toast.success(m.account_passkey_mfa_disabled());
+ await loadAccountData();
+ })()
+ );
+ if (operationResult6.error !== null) {
+ const value = operationResult6.error;
+
showPasskeyError(m.account_passkey_mfa_disable_failed(), value, m.account_passkey_request_failed_description());
}
});
@@ -255,21 +295,29 @@
async function regenerateRecoveryCodes() {
await runWithStepUp(async (stepUpToken) => {
- try {
- const generated = await passkeyService.regenerateRecoveryCodes(stepUpToken);
- recoveryCodes = generated.codes;
- await loadAccountData();
- } catch (value) {
+ const operationResult7 = await tryCatch(
+ (async () => {
+ const generated = await passkeyService.regenerateRecoveryCodes(stepUpToken);
+ recoveryCodes = generated.codes;
+ await loadAccountData();
+ })()
+ );
+ if (operationResult7.error !== null) {
+ const value = operationResult7.error;
+
showPasskeyError(m.account_passkey_mfa_regenerate_failed(), value, m.account_passkey_request_failed_description());
}
});
}
async function copyRecoveryCodes() {
- try {
- await navigator.clipboard.writeText(recoveryCodes.join('\n'));
- toast.success(m.account_passkey_mfa_codes_copied());
- } catch {
+ const operationResult8 = await tryCatch(
+ (async () => {
+ await navigator.clipboard.writeText(recoveryCodes.join('\n'));
+ toast.success(m.account_passkey_mfa_codes_copied());
+ })()
+ );
+ if (operationResult8.error !== null) {
toast.error(m.common_copy_failed());
}
}
diff --git a/frontend/src/lib/components/auth/step-up-dialog.svelte b/frontend/src/lib/components/auth/step-up-dialog.svelte
index 4b76b858d..b0f85f4c6 100644
--- a/frontend/src/lib/components/auth/step-up-dialog.svelte
+++ b/frontend/src/lib/components/auth/step-up-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { startAuthentication, type PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';
import { AlertIcon, ApiKeyIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -46,17 +48,24 @@
busy = true;
error = null;
try {
- const challenge: PasskeyChallenge = await passkeyService.beginStepUp();
- if (!challenge.transactionId) throw new Error(m.account_passkey_step_up_failed());
- const credential = await startAuthentication({
- optionsJSON: challenge.options as unknown as PublicKeyCredentialRequestOptionsJSON
- });
- const grant = await passkeyService.finishStepUp(challenge.transactionId, credential);
- await onResolved(grant);
- open = false;
- } catch (value) {
- if (!(value instanceof Error && value.name === 'NotAllowedError')) {
- error = value instanceof Error ? value.message : m.account_passkey_step_up_failed();
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const challenge: PasskeyChallenge = await passkeyService.beginStepUp();
+ if (!challenge.transactionId) throw new Error(m.account_passkey_step_up_failed());
+ const credential = await startAuthentication({
+ optionsJSON: challenge.options as unknown as PublicKeyCredentialRequestOptionsJSON
+ });
+ const grant = await passkeyService.finishStepUp(challenge.transactionId, credential);
+ await onResolved(grant);
+ open = false;
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const value = operationResult1.error;
+
+ if (!(value instanceof Error && value.name === 'NotAllowedError')) {
+ error = value instanceof Error ? value.message : m.account_passkey_step_up_failed();
+ }
}
} finally {
busy = false;
@@ -70,11 +79,18 @@
busy = true;
error = null;
try {
- const grant = await passkeyService.passwordStepUp(password);
- await onResolved(grant);
- open = false;
- } catch (value) {
- error = value instanceof Error ? value.message : m.account_passkey_step_up_failed();
+ const operationResult2 = await tryCatch(
+ (async () => {
+ const grant = await passkeyService.passwordStepUp(password);
+ await onResolved(grant);
+ open = false;
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const value = operationResult2.error;
+
+ error = value instanceof Error ? value.message : m.account_passkey_step_up_failed();
+ }
} finally {
busy = false;
}
diff --git a/frontend/src/lib/components/backup-file-picker.svelte b/frontend/src/lib/components/backup-file-picker.svelte
index 0733cd505..27ffa0e0b 100644
--- a/frontend/src/lib/components/backup-file-picker.svelte
+++ b/frontend/src/lib/components/backup-file-picker.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import FileTreeRow from '#lib/components/file-tree-row.svelte';
import { Input } from '#lib/components/ui/input/index.js';
@@ -104,25 +106,29 @@
if (current.loading) return;
const requestID = ++nextRequestID;
updatePageInternal(folder, { ...current, loading: true, error: false, requestID });
- try {
- const page = await provider.browse({
- path: searchActive ? undefined : folder,
- search: searchActive ? debouncedSearch : undefined,
- start: start > 0 ? start : undefined
- });
- const latest = pages[folder];
- if (generation !== requestGeneration || latest?.requestID !== requestID) return;
- const merged = replace ? page.data : [...latest.entries, ...page.data];
- const unique = Array.from(new Map(merged.map((entry) => [entry.path, entry])).values());
- const continuationStart = start + page.data.length;
- updatePageInternal(folder, {
- entries: unique,
- continuationStart: continuationStart < page.pagination.totalItems ? continuationStart : undefined,
- loading: false,
- error: false,
- requestID
- });
- } catch {
+
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const page = await provider.browse({
+ path: searchActive ? undefined : folder,
+ search: searchActive ? debouncedSearch : undefined,
+ start: start > 0 ? start : undefined
+ });
+ const latest = pages[folder];
+ if (generation !== requestGeneration || latest?.requestID !== requestID) return;
+ const merged = replace ? page.data : [...latest.entries, ...page.data];
+ const unique = Array.from(new Map(merged.map((entry) => [entry.path, entry])).values());
+ const continuationStart = start + page.data.length;
+ updatePageInternal(folder, {
+ entries: unique,
+ continuationStart: continuationStart < page.pagination.totalItems ? continuationStart : undefined,
+ loading: false,
+ error: false,
+ requestID
+ });
+ })()
+ );
+ if (requestResult1.error !== null) {
const latest = pages[folder];
if (generation !== requestGeneration || latest?.requestID !== requestID) return;
updatePageInternal(folder, { ...latest, loading: false, error: true });
diff --git a/frontend/src/lib/components/backup-policy-dialog.svelte b/frontend/src/lib/components/backup-policy-dialog.svelte
index d876c509c..d5d47c84c 100644
--- a/frontend/src/lib/components/backup-policy-dialog.svelte
+++ b/frontend/src/lib/components/backup-policy-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts" generics="TPolicy extends BackupPolicy, TUpdate extends { id: string } = BackupPolicyUpdate">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { untrack, type Snippet } from 'svelte';
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -103,9 +105,16 @@
async function loadDestinations() {
destinationsLoading = true;
try {
- loadedDestinations = await s3DestinationService.listAll();
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.s3_destinations_load_failed());
+ const operationResult1 = await tryCatch(
+ (async () => {
+ loadedDestinations = await s3DestinationService.listAll();
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
+ toast.error(error instanceof Error ? error.message : m.s3_destinations_load_failed());
+ }
} finally {
destinationsLoading = false;
}
@@ -140,23 +149,30 @@
if (formInvalid) return;
saving = true;
try {
- const current = extendUpdate({
- id: form.id,
- enabled: form.enabled,
- schedule: form.schedule,
- retentionCount: Number(form.retentionCount),
- ...backupPolicyDestinationValues(form.destination, form.s3DestinationId),
- ...(showStopContainers ? { stopContainers: form.stopContainers ?? false } : {})
- });
- const existing = policies.map(policyPayload);
- const next = policyId ? existing.map((policy) => (policy.id === policyId ? current : policy)) : [...existing, current];
- onSaved(await updatePolicies(next));
- open = false;
- toast.success(messages.saved);
- } catch (error) {
- const message = error instanceof Error ? error.message : messages.saveFailed;
- if (/cron|schedule/i.test(message)) form = { ...form, serverError: message };
- else toast.error(message);
+ const operationResult2 = await tryCatch(
+ (async () => {
+ const current = extendUpdate({
+ id: form.id,
+ enabled: form.enabled,
+ schedule: form.schedule,
+ retentionCount: Number(form.retentionCount),
+ ...backupPolicyDestinationValues(form.destination, form.s3DestinationId),
+ ...(showStopContainers ? { stopContainers: form.stopContainers ?? false } : {})
+ });
+ const existing = policies.map(policyPayload);
+ const next = policyId ? existing.map((policy) => (policy.id === policyId ? current : policy)) : [...existing, current];
+ onSaved(await updatePolicies(next));
+ open = false;
+ toast.success(messages.saved);
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const error = operationResult2.error;
+
+ const message = error instanceof Error ? error.message : messages.saveFailed;
+ if (/cron|schedule/i.test(message)) form = { ...form, serverError: message };
+ else toast.error(message);
+ }
} finally {
saving = false;
}
@@ -166,11 +182,18 @@
if (!policyId) return;
deleting = true;
try {
- onSaved(await updatePolicies(policies.filter((policy) => policy.id !== policyId).map(policyPayload)));
- open = false;
- toast.success(messages.removed);
- } catch (error) {
- toast.error(error instanceof Error ? error.message : messages.saveFailed);
+ const operationResult3 = await tryCatch(
+ (async () => {
+ onSaved(await updatePolicies(policies.filter((policy) => policy.id !== policyId).map(policyPayload)));
+ open = false;
+ toast.success(messages.removed);
+ })()
+ );
+ if (operationResult3.error !== null) {
+ const error = operationResult3.error;
+
+ toast.error(error instanceof Error ? error.message : messages.saveFailed);
+ }
} finally {
deleting = false;
}
diff --git a/frontend/src/lib/components/code-editor/analysis/compose-schema.ts b/frontend/src/lib/components/code-editor/analysis/compose-schema.ts
index b06086b56..24bb84af6 100644
--- a/frontend/src/lib/components/code-editor/analysis/compose-schema.ts
+++ b/frontend/src/lib/components/code-editor/analysis/compose-schema.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import Ajv, { type ValidateFunction } from 'ajv';
import type { Completion } from '@codemirror/autocomplete';
import { browser } from '$app/env';
@@ -376,41 +377,50 @@ export async function getComposeSchemaContext(): Promise<ComposeSchemaContext> {
composeSchemaPromise = (async () => {
try {
- const response = await fetch(DOCKER_COMPOSE_SCHEMA_URL, { cache: 'no-store' });
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}`);
- }
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const response = await fetch(DOCKER_COMPOSE_SCHEMA_URL, { cache: 'no-store' });
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+
+ const payload = (await response.json()) as unknown;
+ const schema = asSchemaObject(payload);
+ if (!schema) throw new Error('Invalid compose schema payload');
+
+ writeCachedSchema(schema);
+ composeSchemaContext = {
+ schema,
+ validate: createValidator(schema),
+ status: 'ready'
+ };
+ return composeSchemaContext;
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const error = requestResult1.error;
+
+ const cached = readCachedSchema();
+ if (cached) {
+ composeSchemaContext = {
+ schema: cached,
+ validate: createValidator(cached),
+ status: 'cached',
+ message: 'Using cached Docker Compose schema'
+ };
+ return composeSchemaContext;
+ }
- const payload = (await response.json()) as unknown;
- const schema = asSchemaObject(payload);
- if (!schema) throw new Error('Invalid compose schema payload');
-
- writeCachedSchema(schema);
- composeSchemaContext = {
- schema,
- validate: createValidator(schema),
- status: 'ready'
- };
- return composeSchemaContext;
- } catch (error) {
- const cached = readCachedSchema();
- if (cached) {
composeSchemaContext = {
- schema: cached,
- validate: createValidator(cached),
- status: 'cached',
- message: 'Using cached Docker Compose schema'
+ schema: null,
+ validate: null,
+ status: 'unavailable',
+ message: error instanceof Error ? error.message : 'Schema unavailable'
};
return composeSchemaContext;
+ } else {
+ return requestResult1.data;
}
-
- composeSchemaContext = {
- schema: null,
- validate: null,
- status: 'unavailable',
- message: error instanceof Error ? error.message : 'Schema unavailable'
- };
- return composeSchemaContext;
} finally {
composeSchemaPromise = null;
}
diff --git a/frontend/src/lib/components/compose/ComposeEditorWrapper.svelte b/frontend/src/lib/components/compose/ComposeEditorWrapper.svelte
index e2149c208..33f554658 100644
--- a/frontend/src/lib/components/compose/ComposeEditorWrapper.svelte
+++ b/frontend/src/lib/components/compose/ComposeEditorWrapper.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Alert from '#lib/components/ui/alert/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { AlertIcon, ExternalLinkIcon } from '#lib/icons/index.js';
@@ -33,12 +35,19 @@
async function handleSave() {
isSaving = true;
try {
- await onSave();
- toast.success(m.container_compose_save_success());
- await refreshAll();
- } catch (err: unknown) {
- const message = err instanceof Error ? err.message : m.container_compose_save_failed();
- toast.error(message);
+ const operationResult1 = await tryCatch(
+ (async () => {
+ await onSave();
+ toast.success(m.container_compose_save_success());
+ await refreshAll();
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const err = operationResult1.error;
+
+ const message = err instanceof Error ? err.message : m.container_compose_save_failed();
+ toast.error(message);
+ }
} finally {
isSaving = false;
}
diff --git a/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte b/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte
index d38ceeb2e..372767a89 100644
--- a/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte
+++ b/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte
@@ -6,7 +6,8 @@
import { CopyIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { systemService } from '#lib/services/system-service.js';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { tick } from 'svelte';
import { toast } from 'svelte-sonner';
@@ -39,7 +40,8 @@
return;
}
- handleApiResultWithCallbacks({
+ converting = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(systemService.convert(dockerRunCommand)),
message: m.compose_convert_failed(),
setLoadingState: (value) => (converting = value),
diff --git a/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte b/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
index 3a389c40d..398b030bd 100644
--- a/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
+++ b/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
import * as Dialog from '#lib/components/ui/dialog/index.js';
import { AlertIcon } from '#lib/icons/index.js';
import { confirmDialogStore } from './store';
@@ -22,19 +23,16 @@
}
});
- function handleConfirm() {
+ async function handleConfirm() {
const action = $confirmDialogStore.confirm.action;
const states = $state.snapshot(checkboxStates);
$confirmDialogStore.open = false;
- // The dialog is already closed, so a throwing action would otherwise be an
- // unhandled rejection the user never sees — surface it instead. Invoke
- // inside the chain so synchronous throws also land in the catch.
- Promise.resolve()
- .then(() => action(states))
- .catch((error) => {
- console.error('Confirm action failed:', error);
- toast.error(m.unexpected_error());
- });
+ // Keep synchronous action failures inside the promise boundary.
+ const result = await tryCatch(Promise.resolve().then(() => action(states)));
+ if (result.error !== null) {
+ console.error('Confirm action failed:', result.error);
+ toast.error(m.unexpected_error());
+ }
}
</script>
diff --git a/frontend/src/lib/components/containers/container-form/container-form.svelte b/frontend/src/lib/components/containers/container-form/container-form.svelte
index dcee5b91b..cb3c2b0f4 100644
--- a/frontend/src/lib/components/containers/container-form/container-form.svelte
+++ b/frontend/src/lib/components/containers/container-form/container-form.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import * as Tabs from '#lib/components/ui/tabs/index.js';
import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';
@@ -96,9 +98,12 @@
return;
}
imageSearchTimer = setTimeout(async () => {
- try {
- imageSuggestions = (await imageService.searchImages(term)).slice(0, 6);
- } catch {
+ const operationResult1 = await tryCatch(
+ (async () => {
+ imageSuggestions = (await imageService.searchImages(term)).slice(0, 6);
+ })()
+ );
+ if (operationResult1.error !== null) {
imageSuggestions = [];
}
}, 350);
diff --git a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
index fa8f09c80..0a70bd941 100644
--- a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { Input } from '#lib/components/ui/input/index.js';
@@ -72,22 +74,29 @@
}
try {
- const result = await queryClient.fetchQuery({
- queryKey: queryKeys.environments.switcher(options),
- queryFn: () => environmentManagementService.getEnvironments(options),
- staleTime: 0
- });
- if (requestId !== currentRequestId) return;
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const result = await queryClient.fetchQuery({
+ queryKey: queryKeys.environments.switcher(options),
+ queryFn: () => environmentManagementService.getEnvironments(options),
+ staleTime: 0
+ });
+ if (requestId !== currentRequestId) return;
- environments = append ? [...environments, ...result.data] : result.data;
- currentPage = result.pagination.currentPage;
- totalPages = result.pagination.totalPages;
- } catch (error) {
- if (requestId !== currentRequestId) return;
- console.error('Failed to load environments:', error);
- loadError = 'Failed to load environments';
- toast.error(loadError);
- if (throwOnError) throw error;
+ environments = append ? [...environments, ...result.data] : result.data;
+ currentPage = result.pagination.currentPage;
+ totalPages = result.pagination.totalPages;
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const error = requestResult1.error;
+
+ if (requestId !== currentRequestId) return;
+ console.error('Failed to load environments:', error);
+ loadError = 'Failed to load environments';
+ toast.error(loadError);
+ if (throwOnError) throw error;
+ }
} finally {
if (requestId !== currentRequestId) return;
isLoading = false;
@@ -196,15 +205,20 @@
if (currentPage >= totalPages) return;
isLoadingMore = true;
try {
- const options: SearchPaginationSortRequest = {
- ...requestOptions,
- search: normalizeSearch(searchQuery),
- pagination: { page: currentPage + 1, limit: PAGE_SIZE },
- sort: { column: 'name', direction: 'asc' }
- };
- await fetchEnvironments(options, true, false);
- } catch {
- // fetchEnvironments already handles toasts/errors (and stale-response protection)
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const options: SearchPaginationSortRequest = {
+ ...requestOptions,
+ search: normalizeSearch(searchQuery),
+ pagination: { page: currentPage + 1, limit: PAGE_SIZE },
+ sort: { column: 'name', direction: 'asc' }
+ };
+ await fetchEnvironments(options, true, false);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ // fetchEnvironments already handles toasts/errors (and stale-response protection)
+ }
} finally {
// fetchEnvironments controls isLoadingMore; this is only a safety net.
isLoadingMore = false;
@@ -213,11 +227,17 @@
async function handleSelect(env: Environment) {
if (!env || !env.enabled) return;
- try {
- await environmentStore.setEnvironment(env);
- closeDialog();
- toast.success(m.environments_switched_to({ name: env.name }));
- } catch (error) {
+
+ const operationResult2 = await tryCatch(
+ (async () => {
+ await environmentStore.setEnvironment(env);
+ closeDialog();
+ toast.success(m.environments_switched_to({ name: env.name }));
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const error = operationResult2.error;
+
console.error('Failed to set environment:', error);
toast.error(m.environments_connect_error());
}
diff --git a/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte b/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
index a7493cae3..51ee671c8 100644
--- a/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import * as InputGroup from '#lib/components/ui/input-group/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -52,10 +54,17 @@
isSearching = true;
hasSearched = true;
try {
- results = await imageService.searchImages(term);
- } catch (error) {
- console.error('Failed to search images:', error);
- toast.error(m.images_search_failed());
+ const operationResult1 = await tryCatch(
+ (async () => {
+ results = await imageService.searchImages(term);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
+ console.error('Failed to search images:', error);
+ toast.error(m.images_search_failed());
+ }
} finally {
isSearching = false;
}
diff --git a/frontend/src/lib/components/dialogs/template-selection-dialog.svelte b/frontend/src/lib/components/dialogs/template-selection-dialog.svelte
index 2876c6ba0..18df01d26 100644
--- a/frontend/src/lib/components/dialogs/template-selection-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/template-selection-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { Card } from '#lib/components/ui/card/index.js';
@@ -110,22 +112,29 @@
loadingStates.add(loadingKey);
try {
- const details = await selectTemplateMutation.mutateAsync(template);
- if (!details) {
- toast.error(m.templates_load_failed());
- return;
- }
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const details = await selectTemplateMutation.mutateAsync(template);
+ if (!details) {
+ toast.error(m.templates_load_failed());
+ return;
+ }
+
+ onSelect({
+ ...details.template,
+ content: details.content,
+ envContent: details.envContent
+ });
+ open = false;
+ toast.success(m.templates_loaded_success({ name: template.name }));
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const error = requestResult1.error;
- onSelect({
- ...details.template,
- content: details.content,
- envContent: details.envContent
- });
- open = false;
- toast.success(m.templates_loaded_success({ name: template.name }));
- } catch (error) {
- console.error('Error loading template:', error);
- toast.error(error instanceof Error ? error.message : m.templates_load_failed());
+ console.error('Error loading template:', error);
+ toast.error(error instanceof Error ? error.message : m.templates_load_failed());
+ }
} finally {
loadingStates.delete(loadingKey);
}
@@ -138,16 +147,23 @@
loadingStates.add(loadingKey);
try {
- const result = await downloadTemplateMutation.mutateAsync(template);
- if (result) {
- toast.success(m.templates_downloaded_success({ name: template.name }));
- onDownloadSuccess?.();
- } else {
- toast.error(m.templates_download_failed());
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const result = await downloadTemplateMutation.mutateAsync(template);
+ if (result) {
+ toast.success(m.templates_downloaded_success({ name: template.name }));
+ onDownloadSuccess?.();
+ } else {
+ toast.error(m.templates_download_failed());
+ }
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
+ console.error('Error downloading template:', error);
+ toast.error(error instanceof Error ? error.message : m.templates_download_failed());
}
- } catch (error) {
- console.error('Error downloading template:', error);
- toast.error(error instanceof Error ? error.message : m.templates_download_failed());
} finally {
loadingStates.delete(loadingKey);
}
diff --git a/frontend/src/lib/components/dialogs/update-all-dialog.svelte b/frontend/src/lib/components/dialogs/update-all-dialog.svelte
index 6b61bf70e..e2388fca4 100644
--- a/frontend/src/lib/components/dialogs/update-all-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/update-all-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Dialog from '#lib/components/ui/dialog/index.js';
import * as ScrollArea from '#lib/components/ui/scroll-area/index.js';
import { Button } from '#lib/components/ui/button/index.js';
@@ -87,20 +89,26 @@
async function poll() {
if (!pollActive) return;
- try {
- const next = await systemUpgradeService.getUpdateAllStatus();
- reconnecting = false;
- job = next;
- if (next.status === 'completed' || next.status === 'failed') {
- stopPolling();
- finishTerminalJob(next);
- return;
- }
- } catch {
+
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const next = await systemUpgradeService.getUpdateAllStatus();
+ reconnecting = false;
+ job = next;
+ if (next.status === 'completed' || next.status === 'failed') {
+ stopPolling();
+ finishTerminalJob(next);
+ return true;
+ }
+ })()
+ );
+ if (requestResult1.error !== null) {
// The manager is likely restarting after its own upgrade — keep retrying
// until the backend answers again.
reconnecting = true;
}
+ if (requestResult1.data) return;
+
schedulePoll();
}
@@ -114,9 +122,13 @@
}
BaseAPIService.setUpgradeInProgress(true);
- try {
- job = await systemUpgradeService.triggerUpdateAll();
- } catch {
+
+ const operationResult1 = await tryCatch(
+ (async () => {
+ job = await systemUpgradeService.triggerUpdateAll();
+ })()
+ );
+ if (operationResult1.error !== null) {
toast.error(m.environments_update_all_trigger_failed());
resetState();
return;
@@ -139,9 +151,12 @@
// lands while agents are still reconnecting after the fleet restart, which
// renders every environment as offline for a moment.
if (job && !debugDemo) {
- try {
- await refreshAll();
- } catch {
+ const operationResult2 = await tryCatch(
+ (async () => {
+ await refreshAll();
+ })()
+ );
+ if (operationResult2.error !== null) {
// A failed refresh must not trap the dialog open.
}
}
diff --git a/frontend/src/lib/components/dialogs/update-center-dialog.svelte b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
index 5a8610607..d37214f3e 100644
--- a/frontend/src/lib/components/dialogs/update-center-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Dialog from '#lib/components/ui/dialog/index.js';
import * as ScrollArea from '#lib/components/ui/scroll-area/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -209,89 +211,95 @@
}
}
- try {
- const info = await systemUpgradeService.getVersionInfo(envId);
- successfulPolls += 1;
-
- // Promote a hung trigger to "resolved" once the agent has answered
- // at least 2 unrelated requests successfully. The agent is alive and
- // has had time to act on our POST — its response just never came back.
- if (triggerResolvedAt === null && successfulPolls >= 2) {
- triggerResolvedAt = performance.now();
- log('trigger-implicit-resolved', {
- reason: 'agent-answered-poll-without-trigger-response',
- successfulPolls
- });
- }
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const info = await systemUpgradeService.getVersionInfo(envId);
+ successfulPolls += 1;
+
+ // Promote a hung trigger to "resolved" once the agent has answered
+ // at least 2 unrelated requests successfully. The agent is alive and
+ // has had time to act on our POST — its response just never came back.
+ if (triggerResolvedAt === null && successfulPolls >= 2) {
+ triggerResolvedAt = performance.now();
+ log('trigger-implicit-resolved', {
+ reason: 'agent-answered-poll-without-trigger-response',
+ successfulPolls
+ });
+ }
- const expVer = expectedVersion?.trim();
- const expDig = expectedDigest?.trim();
- const ok = matchesExpected(info);
- const changed = versionInfoChanged(baselineVersionInfo, info);
-
- const triggerSettledAt = triggerResolvedAt;
- const sinceTriggerMs = triggerSettledAt === null ? null : performance.now() - triggerSettledAt;
-
- log('version-check', {
- currentVersion: info.currentVersion,
- currentDigest: short(info.currentDigest),
- revision: short(info.revision, 8),
- baselineVersion: baselineVersionInfo?.currentVersion,
- baselineDigest: short(baselineVersionInfo?.currentDigest),
- expVer,
- expDig: short(expDig),
- ok,
- changed,
- sinceTriggerMs,
- successfulPolls
- });
+ const expVer = expectedVersion?.trim();
+ const expDig = expectedDigest?.trim();
+ const ok = matchesExpected(info);
+ const changed = versionInfoChanged(baselineVersionInfo, info);
- const verified = expVer || expDig ? ok : !!baselineVersionInfo && changed;
- if (verified) {
- log('verified', {
- mode: expVer || expDig ? 'expected' : 'baseline-change',
- currentVersion: info.currentVersion,
- currentDigest: short(info.currentDigest)
- });
- upgradeStatus = 'ready';
- if (isRemoteEnvironment) {
- setTimeout(() => (upgradeStatus = 'complete'), 1500);
- } else {
- reloadPage();
- }
- return;
- }
+ const triggerSettledAt = triggerResolvedAt;
+ const sinceTriggerMs = triggerSettledAt === null ? null : performance.now() - triggerSettledAt;
- // no-op detection: trigger API has returned successfully,
- // the agent has had NO_OP_GRACE_MS to begin a restart, and the version
- // has not moved from baseline. Conclusion: there was nothing to do.
- if (
- !expVer &&
- !expDig &&
- !!baselineVersionInfo &&
- !changed &&
- sinceTriggerMs !== null &&
- (reportedUpToDate || sinceTriggerMs >= NO_OP_GRACE_MS)
- ) {
- log('no-op-detected', {
- reportedUpToDate,
- sinceTriggerMs,
+ log('version-check', {
+ currentVersion: info.currentVersion,
currentDigest: short(info.currentDigest),
- baselineDigest: short(baselineVersionInfo?.currentDigest)
+ revision: short(info.revision, 8),
+ baselineVersion: baselineVersionInfo?.currentVersion,
+ baselineDigest: short(baselineVersionInfo?.currentDigest),
+ expVer,
+ expDig: short(expDig),
+ ok,
+ changed,
+ sinceTriggerMs,
+ successfulPolls
});
- upgradeStatus = 'ready';
- setTimeout(() => {
+
+ const verified = expVer || expDig ? ok : !!baselineVersionInfo && changed;
+ if (verified) {
+ log('verified', {
+ mode: expVer || expDig ? 'expected' : 'baseline-change',
+ currentVersion: info.currentVersion,
+ currentDigest: short(info.currentDigest)
+ });
+ upgradeStatus = 'ready';
if (isRemoteEnvironment) {
- upgradeStatus = 'complete';
+ setTimeout(() => (upgradeStatus = 'complete'), 1500);
} else {
- closeAfterComplete();
+ reloadPage();
}
- }, 600);
- return;
- }
- } catch (err) {
+ return true;
+ }
+
+ // no-op detection: trigger API has returned successfully,
+ // the agent has had NO_OP_GRACE_MS to begin a restart, and the version
+ // has not moved from baseline. Conclusion: there was nothing to do.
+ if (
+ !expVer &&
+ !expDig &&
+ !!baselineVersionInfo &&
+ !changed &&
+ sinceTriggerMs !== null &&
+ (reportedUpToDate || sinceTriggerMs >= NO_OP_GRACE_MS)
+ ) {
+ log('no-op-detected', {
+ reportedUpToDate,
+ sinceTriggerMs,
+ currentDigest: short(info.currentDigest),
+ baselineDigest: short(baselineVersionInfo?.currentDigest)
+ });
+ upgradeStatus = 'ready';
+ setTimeout(() => {
+ if (isRemoteEnvironment) {
+ upgradeStatus = 'complete';
+ } else {
+ closeAfterComplete();
+ }
+ }, 600);
+ return true;
+ }
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const err = requestResult1.error;
+
log('version-endpoint-error', err);
}
+ if (requestResult1.data) return;
await new Promise((r) => setTimeout(r, 2000));
}
@@ -313,21 +321,26 @@
}
async function captureBaseline() {
- try {
- baselineVersionInfo = await queryClient.fetchQuery({
- queryKey: queryKeys.system.versionInfo(environmentId ?? '0'),
- queryFn: () => systemUpgradeService.getVersionInfo(environmentId ?? '0'),
- staleTime: 0
- });
- if (!baselineVersionInfo) return;
+ const requestResult2 = await tryCatch(
+ (async () => {
+ baselineVersionInfo = await queryClient.fetchQuery({
+ queryKey: queryKeys.system.versionInfo(environmentId ?? '0'),
+ queryFn: () => systemUpgradeService.getVersionInfo(environmentId ?? '0'),
+ staleTime: 0
+ });
+ if (!baselineVersionInfo) return;
+
+ const baseline = baselineVersionInfo;
+ log('baseline', {
+ currentVersion: baseline.currentVersion,
+ currentDigest: short(baseline.currentDigest),
+ revision: short(baseline.revision, 8)
+ });
+ })()
+ );
+ if (requestResult2.error !== null) {
+ const err = requestResult2.error;
- const baseline = baselineVersionInfo;
- log('baseline', {
- currentVersion: baseline.currentVersion,
- currentDigest: short(baseline.currentDigest),
- revision: short(baseline.revision, 8)
- });
- } catch (err) {
log('baseline-error', err);
baselineVersionInfo = null;
}
@@ -362,17 +375,21 @@
triggerResolvedAt = null;
reportedUpToDate = false;
let triggerErrored = false;
- const triggerPromise = Promise.resolve()
- .then(() => onConfirm())
- .then((result) => {
- triggerResolvedAt = performance.now();
- reportedUpToDate = !!result && result.upToDate === true;
- log('trigger-resolved', { upToDate: reportedUpToDate });
- })
- .catch((err) => {
- log('trigger-error', err);
+ const triggerPromise = (async () => {
+ const result = await tryCatch(
+ Promise.resolve()
+ .then(() => onConfirm())
+ .then((result) => {
+ triggerResolvedAt = performance.now();
+ reportedUpToDate = !!result && result.upToDate === true;
+ log('trigger-resolved', { upToDate: reportedUpToDate });
+ })
+ );
+ if (result.error !== null) {
+ log('trigger-error', result.error);
triggerErrored = true;
- });
+ }
+ })();
await Promise.race([triggerPromise, new Promise((r) => setTimeout(r, 1500))]);
diff --git a/frontend/src/lib/components/dialogs/version-info-dialog.svelte b/frontend/src/lib/components/dialogs/version-info-dialog.svelte
index aa9d287a5..088e06635 100644
--- a/frontend/src/lib/components/dialogs/version-info-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/version-info-dialog.svelte
@@ -11,7 +11,8 @@
import { hasPermission } from '#lib/utils/auth.js';
import settingsStore from '#lib/stores/config-store.js';
import { settingsService } from '#lib/services/settings-service.js';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
interface Props {
@@ -48,7 +49,8 @@
let savingExperimental = $state(false);
async function handleExperimentalToggle(enabled: boolean) {
- handleApiResultWithCallbacks<Settings>({
+ savingExperimental = true;
+ await handleApiResultWithCallbacks<Settings>({
result: await tryCatch(settingsService.updateSettings({ experimentalFeaturesEnabled: enabled })),
message: m.common_update_failed({ resource: m.settings() }),
setLoadingState: (value) => (savingExperimental = value),
diff --git a/frontend/src/lib/components/file-browser/CreateFolderDialog.svelte b/frontend/src/lib/components/file-browser/CreateFolderDialog.svelte
index 13606625b..823b9dc27 100644
--- a/frontend/src/lib/components/file-browser/CreateFolderDialog.svelte
+++ b/frontend/src/lib/components/file-browser/CreateFolderDialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Dialog from '#lib/components/ui/dialog/index.js';
import { Button } from '#lib/components/ui/button/index.js';
import { Input } from '#lib/components/ui/input/index.js';
@@ -26,12 +28,19 @@
loading = true;
try {
- const result = await onCreate(folderName);
- toast.success(m.common_create_success({ resource: folderName }), activityToastOptions(extractActivityId(result)));
- open = false;
- folderName = '';
- } catch (e: any) {
- toast.error(e.message || m.common_create_failed({ resource: folderName }));
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const result = await onCreate(folderName);
+ toast.success(m.common_create_success({ resource: folderName }), activityToastOptions(extractActivityId(result)));
+ open = false;
+ folderName = '';
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const e = operationResult1.error;
+
+ toast.error(e.message || m.common_create_failed({ resource: folderName }));
+ }
} finally {
loading = false;
}
diff --git a/frontend/src/lib/components/file-browser/FileList.svelte b/frontend/src/lib/components/file-browser/FileList.svelte
index c3e24c80c..52af6ccdd 100644
--- a/frontend/src/lib/components/file-browser/FileList.svelte
+++ b/frontend/src/lib/components/file-browser/FileList.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import type { FileEntry } from '#lib/types/shared.js';
import {
FolderOpenIcon,
@@ -111,11 +113,16 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- try {
- const result = await onDelete(file);
- toast.success(m.common_delete_success({ resource: file.name }), activityToastOptions(extractActivityId(result)));
- onRefresh();
- } catch (e: any) {
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const result = await onDelete(file);
+ toast.success(m.common_delete_success({ resource: file.name }), activityToastOptions(extractActivityId(result)));
+ onRefresh();
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const e = operationResult1.error;
+
toast.error(e.message || m.common_delete_failed({ resource: file.name }));
}
}
@@ -124,9 +131,14 @@
}
async function handleDownload(file: FileEntry) {
- try {
- await onDownload(file);
- } catch (e: any) {
+ const operationResult2 = await tryCatch(
+ (async () => {
+ await onDownload(file);
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const e = operationResult2.error;
+
toast.error(e.message || m.common_failed());
}
}
diff --git a/frontend/src/lib/components/file-browser/FilePreview.svelte b/frontend/src/lib/components/file-browser/FilePreview.svelte
index 5755409c5..6b04e4de3 100644
--- a/frontend/src/lib/components/file-browser/FilePreview.svelte
+++ b/frontend/src/lib/components/file-browser/FilePreview.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import type { FileEntry } from '#lib/types/shared.js';
import { onMount } from 'svelte';
import * as Sheet from '#lib/components/ui/sheet/index.js';
@@ -30,10 +32,17 @@
onMount(async () => {
try {
- const res = await fetchContent(file.path);
- content = b64DecodeUnicode(res);
- } catch (e: any) {
- error = e.message || 'Failed to load preview';
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const res = await fetchContent(file.path);
+ content = b64DecodeUnicode(res);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const e = operationResult1.error;
+
+ error = e.message || 'Failed to load preview';
+ }
} finally {
loading = false;
}
diff --git a/frontend/src/lib/components/file-browser/FileUploadDialog.svelte b/frontend/src/lib/components/file-browser/FileUploadDialog.svelte
index ded8ea45b..e34045f41 100644
--- a/frontend/src/lib/components/file-browser/FileUploadDialog.svelte
+++ b/frontend/src/lib/components/file-browser/FileUploadDialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Dialog from '#lib/components/ui/dialog/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { FileDropZone, displaySize, type FileDropZoneProps } from '#lib/components/ui/file-drop-zone/index.js';
@@ -40,17 +42,24 @@
if (files.length === 0) return;
uploading = true;
try {
- let lastResult: unknown;
- for (const file of files) {
- uploadingFile = file.name;
- uploadProgress = null;
- lastResult = await onUploadAction(file, (progress) => (uploadProgress = progress));
+ const operationResult1 = await tryCatch(
+ (async () => {
+ let lastResult: unknown;
+ for (const file of files) {
+ uploadingFile = file.name;
+ uploadProgress = null;
+ lastResult = await onUploadAction(file, (progress) => (uploadProgress = progress));
+ }
+ toast.success(m.common_success(), activityToastOptions(extractActivityId(lastResult)));
+ open = false;
+ files = [];
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const e = operationResult1.error;
+
+ toast.error(e.message || m.common_failed());
}
- toast.success(m.common_success(), activityToastOptions(extractActivityId(lastResult)));
- open = false;
- files = [];
- } catch (e: any) {
- toast.error(e.message || m.common_failed());
} finally {
uploading = false;
uploadingFile = null;
diff --git a/frontend/src/lib/components/font-size-picker.svelte b/frontend/src/lib/components/font-size-picker.svelte
index 56c12f8ad..e3c0554f3 100644
--- a/frontend/src/lib/components/font-size-picker.svelte
+++ b/frontend/src/lib/components/font-size-picker.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Slider from '#lib/components/ui/slider/index.js';
import userStore from '#lib/stores/user-store.js';
import { userService } from '#lib/services/user-service.js';
@@ -19,11 +21,17 @@
const persist = debounced(async (px: number) => {
const previous = lastPersisted;
- try {
- await userService.updateMyProfile({ fontSize: px });
- lastPersisted = px;
- await queryClient.invalidateQueries({ queryKey: queryKeys.users.all });
- } catch (err) {
+
+ const operationResult1 = await tryCatch(
+ (async () => {
+ await userService.updateMyProfile({ fontSize: px });
+ lastPersisted = px;
+ await queryClient.invalidateQueries({ queryKey: queryKeys.users.all });
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const err = operationResult1.error;
+
console.error('Failed to update font size', err);
currentSize = previous;
applyFontSize(previous);
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index 79476d63d..244e6dd1e 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { Badge, type BadgeVariant } from '#lib/components/ui/badge/index.js';
import { toast } from 'svelte-sonner';
@@ -167,39 +169,44 @@
async function checkImageUpdate() {
if (!canCheckUpdate || imageUpdateQuery.isFetching) return;
- try {
- const result = await imageUpdateQuery.refetch();
- if (result.data) {
- onUpdated?.(result.data);
- const toastOptions = activityToastOptions(extractActivityId(result.data));
+ const requestResult1 = await tryCatch(
+ (async () => {
+ const result = await imageUpdateQuery.refetch();
+ if (result.data) {
+ onUpdated?.(result.data);
+ const toastOptions = activityToastOptions(extractActivityId(result.data));
+
+ if (result.data.error) {
+ toast.error(result.data.error || m.images_update_check_failed(), toastOptions);
+ } else {
+ toast.success(m.images_update_check_completed(), toastOptions);
+ }
+ return;
+ }
- if (result.data.error) {
- toast.error(result.data.error || m.images_update_check_failed(), toastOptions);
- } else {
- toast.success(m.images_update_check_completed(), toastOptions);
+ if (result.error) {
+ const message = result.error instanceof Error ? result.error.message : m.images_update_check_failed();
+ onUpdated?.({
+ hasUpdate: false,
+ updateType: 'error',
+ currentVersion: tag || '',
+ currentDigest: '',
+ latestVersion: '',
+ latestDigest: '',
+ checkTime: nowInstantString(),
+ responseTimeMs: 0,
+ error: message
+ });
+ toast.error(message);
+ return;
}
- return;
- }
-
- if (result.error) {
- const message = result.error instanceof Error ? result.error.message : m.images_update_check_failed();
- onUpdated?.({
- hasUpdate: false,
- updateType: 'error',
- currentVersion: tag || '',
- currentDigest: '',
- latestVersion: '',
- latestDigest: '',
- checkTime: nowInstantString(),
- responseTimeMs: 0,
- error: message
- });
- toast.error(message);
- return;
- }
-
- toast.error(m.images_update_check_failed());
- } catch (error) {
+
+ toast.error(m.images_update_check_failed());
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const error = requestResult1.error;
+
console.error('Error checking update:', error);
const errorInfo: ImageUpdateData = {
hasUpdate: false,
diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelte
index 2d71b400e..f9c562c30 100644
--- a/frontend/src/lib/components/logs/log-viewer.svelte
+++ b/frontend/src/lib/components/logs/log-viewer.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
// Dozzle reference: the grouped row shell and left-side timestamp treatment here were
// informed by amir20/dozzle's LogItem.vue and GroupedLogItem.vue.
import { dev } from '$app/env';
@@ -207,20 +209,27 @@
const sessionId = ++streamSession;
currentStreamSession = sessionId;
try {
- shouldBeStreaming = true;
- error = null;
- await startWebSocketStream(sessionId);
- // Only notify after successful start
- isStreaming = true;
- onStart?.();
- return;
- } catch (err) {
- console.error('Failed to start log stream:', err);
- error = m.log_stream_failed_connect({ type: humanType });
- isStreaming = false;
- shouldBeStreaming = false;
- if (currentStreamSession === sessionId) {
- currentStreamSession = 0;
+ const requestResult1 = await tryCatch(
+ (async () => {
+ shouldBeStreaming = true;
+ error = null;
+ await startWebSocketStream(sessionId);
+ // Only notify after successful start
+ isStreaming = true;
+ onStart?.();
+ return;
+ })()
+ );
+ if (requestResult1.error !== null) {
+ const err = requestResult1.error;
+
+ console.error('Failed to start log stream:', err);
+ error = m.log_stream_failed_connect({ type: humanType });
+ isStreaming = false;
+ shouldBeStreaming = false;
+ if (currentStreamSession === sessionId) {
+ currentStreamSession = 0;
+ }
}
} finally {
connecting = false;
diff --git a/frontend/src/lib/components/logs/structured-log-entry.svelte b/frontend/src/lib/components/logs/structured-log-entry.svelte
index 69da40a88..956536aca 100644
--- a/frontend/src/lib/components/logs/structured-log-entry.svelte
+++ b/frontend/src/lib/components/logs/structured-log-entry.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
// Dozzle reference: the compact structured-log summary and expandable details pattern
// here were informed by amir20/dozzle's ComplexLogItem.vue and LogDetails.vue.
import * as Collapsible from '#lib/components/ui/collapsible/index.js';
@@ -226,13 +228,18 @@
const hasDetails = $derived(summaryFields.length > SUMMARY_LIMIT || summaryFields.length > 0 || !!rawJson);
async function copyToClipboard() {
- try {
- await navigator.clipboard.writeText(jsonString);
- copied = true;
- setTimeout(() => {
- copied = false;
- }, 2000);
- } catch (err) {
+ const operationResult1 = await tryCatch(
+ (async () => {
+ await navigator.clipboard.writeText(jsonString);
+ copied = true;
+ setTimeout(() => {
+ copied = false;
+ }, 2000);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const err = operationResult1.error;
+
console.error('Failed to copy to clipboard:', err);
}
}
diff --git a/frontend/src/lib/components/project-tag-editor.svelte b/frontend/src/lib/components/project-tag-editor.svelte
index 05b718cc0..8cc26d098 100644
--- a/frontend/src/lib/components/project-tag-editor.svelte
+++ b/frontend/src/lib/components/project-tag-editor.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import type { ProjectTag, ProjectTagColor, ProjectTagOption } from '#lib/types/swarm.js';
import * as Command from '#lib/components/ui/command/index.js';
import * as Popover from '#lib/components/ui/popover/index.js';
@@ -110,13 +112,20 @@
: tags.filter((tag) => tag.name !== normalized);
pending = normalized;
try {
- const updated = await onToggle?.(normalized, attached, resolvedColor);
- if (updated) tags = updated;
- search = '';
- selectedColor = 'gray';
- } catch (error) {
- tags = previous;
- toast.error(error instanceof Error ? error.message : m.common_error());
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const updated = await onToggle?.(normalized, attached, resolvedColor);
+ if (updated) tags = updated;
+ search = '';
+ selectedColor = 'gray';
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
+ tags = previous;
+ toast.error(error instanceof Error ? error.message : m.common_error());
+ }
} finally {
pending = null;
}
diff --git a/frontend/src/lib/components/settings/trivy-security-settings.svelte b/frontend/src/lib/components/settings/trivy-security-settings.svelte
index 87351816c..fde75b5d7 100644
--- a/frontend/src/lib/components/settings/trivy-security-settings.svelte
+++ b/frontend/src/lib/components/settings/trivy-security-settings.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { Switch } from '#lib/components/ui/switch/index.js';
import { Textarea } from '#lib/components/ui/textarea/index.js';
import * as Alert from '#lib/components/ui/alert/index.js';
@@ -132,18 +133,17 @@
const targetEnvironmentId = environmentId;
let cancelled = false;
- void fetchTrivyNetworkOptions(targetEnvironmentId)
- .then((options) => {
- if (!cancelled) {
- customTrivyNetworkOptions = options;
- }
- })
- .catch((error) => {
- if (!cancelled) {
- console.warn('Failed to load Trivy network options:', error);
- toast.info(m.security_trivy_network_fetch_failed());
- }
- });
+ void (async () => {
+ const result = await tryCatch(
+ fetchTrivyNetworkOptions(targetEnvironmentId).then((options) => {
+ if (!cancelled) customTrivyNetworkOptions = options;
+ })
+ );
+ if (result.error !== null && !cancelled) {
+ console.warn('Failed to load Trivy network options:', result.error);
+ toast.info(m.security_trivy_network_fetch_failed());
+ }
+ })();
return () => {
cancelled = true;
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
index a2ac1cee1..e34cd57e8 100644
--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { toast } from 'svelte-sonner';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import * as Tabs from '#lib/components/ui/tabs/index.js';
@@ -61,22 +63,29 @@
isLoadingSnippets = true;
try {
- const snippets = await queryClient.fetchQuery({
- queryKey: queryKeys.environments.deploymentSnippets(created.id),
- queryFn: () => environmentManagementService.getDeploymentSnippets(created.id),
- staleTime: 0
- });
- const useGeneratedMTLS = variables.useMTLS && !!snippets.mtls;
- if (variables.useMTLS && !snippets.mtls) {
- toast.warning(m.environments_new_agent_mtls_assets_unavailable());
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const snippets = await queryClient.fetchQuery({
+ queryKey: queryKeys.environments.deploymentSnippets(created.id),
+ queryFn: () => environmentManagementService.getDeploymentSnippets(created.id),
+ staleTime: 0
+ });
+ const useGeneratedMTLS = variables.useMTLS && !!snippets.mtls;
+ if (variables.useMTLS && !snippets.mtls) {
+ toast.warning(m.environments_new_agent_mtls_assets_unavailable());
+ }
+
+ createdEnvironment.dockerRun = useGeneratedMTLS ? snippets.mtls!.dockerRun : snippets.dockerRun;
+ createdEnvironment.dockerCompose = useGeneratedMTLS ? snippets.mtls!.dockerCompose : snippets.dockerCompose;
+ createdEnvironment.mtlsEnabled = useGeneratedMTLS;
+ createdEnvironment.mtlsFiles = useGeneratedMTLS ? snippets.mtls!.files : [];
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const err = operationResult1.error;
+
+ console.error('Failed to fetch deployment snippets:', err);
}
-
- createdEnvironment.dockerRun = useGeneratedMTLS ? snippets.mtls!.dockerRun : snippets.dockerRun;
- createdEnvironment.dockerCompose = useGeneratedMTLS ? snippets.mtls!.dockerCompose : snippets.dockerCompose;
- createdEnvironment.mtlsEnabled = useGeneratedMTLS;
- createdEnvironment.mtlsFiles = useGeneratedMTLS ? snippets.mtls!.files : [];
- } catch (err) {
- console.error('Failed to fetch deployment snippets:', err);
} finally {
isLoadingSnippets = false;
}
@@ -193,21 +202,28 @@
toast.error(m.common_download_error());
return;
}
- try {
- const response = await fetch(file.downloadUrl, { credentials: 'include' });
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}`);
- }
- const blob = await response.blob();
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = file.name;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- } catch (err) {
+
+ const downloadUrl = file.downloadUrl;
+ const operationResult2 = await tryCatch(
+ (async () => {
+ const response = await fetch(downloadUrl, { credentials: 'include' });
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ const blob = await response.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = file.name;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ })()
+ );
+ if (operationResult2.error !== null) {
+ const err = operationResult2.error;
+
console.error('Failed to download mTLS asset:', err);
toast.error(m.common_download_error());
}
diff --git a/frontend/src/lib/components/sheets/webhook-form-sheet.svelte b/frontend/src/lib/components/sheets/webhook-form-sheet.svelte
index 7b1fecaf5..f04197b32 100644
--- a/frontend/src/lib/components/sheets/webhook-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/webhook-form-sheet.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import FormInput from '#lib/components/form/form-input.svelte';
@@ -103,25 +105,30 @@
const generation = ++loadGeneration;
targetOptionsLoading = true;
try {
- const envId = await environmentStore.getCurrentEnvironmentId();
- let options: { label: string; value: string }[] = [];
- if (type === 'container') {
- const res = await containerService.getContainersForEnvironment(envId, { pagination: { page: 1, limit: 200 } });
- options = res.data.map((c) => ({ value: c.id, label: c.names[0]?.replace(/^\//, '') ?? c.id }));
- } else if (type === 'project') {
- const res = await projectService.getProjectsForEnvironment(envId, { pagination: { page: 1, limit: 200 } });
- options = res.data.map((p) => ({ value: p.id, label: p.name }));
- } else if (type === 'gitops') {
- const res = await gitOpsSyncService.getSyncs(envId, { pagination: { page: 1, limit: 200 } });
- options = res.data.map((s) => ({ value: s.id, label: s.name }));
- }
- if (generation === loadGeneration) {
- targetOptions = options;
- selectedTargetId = options[0]?.value ?? '';
- }
- } catch {
- if (generation === loadGeneration) {
- targetOptions = [];
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ let options: { label: string; value: string }[] = [];
+ if (type === 'container') {
+ const res = await containerService.getContainersForEnvironment(envId, { pagination: { page: 1, limit: 200 } });
+ options = res.data.map((c) => ({ value: c.id, label: c.names[0]?.replace(/^\//, '') ?? c.id }));
+ } else if (type === 'project') {
+ const res = await projectService.getProjectsForEnvironment(envId, { pagination: { page: 1, limit: 200 } });
+ options = res.data.map((p) => ({ value: p.id, label: p.name }));
+ } else if (type === 'gitops') {
+ const res = await gitOpsSyncService.getSyncs(envId, { pagination: { page: 1, limit: 200 } });
+ options = res.data.map((s) => ({ value: s.id, label: s.name }));
+ }
+ if (generation === loadGeneration) {
+ targetOptions = options;
+ selectedTargetId = options[0]?.value ?? '';
+ }
+ })()
+ );
+ if (operationResult1.error !== null) {
+ if (generation === loadGeneration) {
+ targetOptions = [];
+ }
}
} finally {
if (generation === loadGeneration) {
diff --git a/frontend/src/lib/components/swarm/swarm-kv-page.svelte b/frontend/src/lib/components/swarm/swarm-kv-page.svelte
index 62248c8ed..42fc9bfa8 100644
--- a/frontend/src/lib/components/swarm/swarm-kv-page.svelte
+++ b/frontend/src/lib/components/swarm/swarm-kv-page.svelte
@@ -10,7 +10,8 @@
import { TrashIcon } from '#lib/icons/index.js';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
import { m } from '#lib/paraglide/messages.js';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { decodeBase64ToText, encodeTextToBase64, formatSwarmTimestamp, getSwarmSpecName } from '#lib/utils/swarm-kv.js';
import { onMount, type Component } from 'svelte';
import { toast } from 'svelte-sonner';
@@ -130,7 +131,8 @@
Data: encodeTextToBase64(createData)
};
- handleApiResultWithCallbacks({
+ isLoading.create = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(createItem(spec)),
message: messages.createFailed,
setLoadingState: (value) => (isLoading.create = value),
@@ -153,7 +155,8 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isLoading.delete = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(removeItem(item.id)),
message: messages.deleteFailed(name),
setLoadingState: (value) => (isLoading.delete = value),
diff --git a/frontend/src/lib/components/theme-mode/theme-mode-selector.svelte b/frontend/src/lib/components/theme-mode/theme-mode-selector.svelte
index d07f75c01..9deeffbb5 100644
--- a/frontend/src/lib/components/theme-mode/theme-mode-selector.svelte
+++ b/frontend/src/lib/components/theme-mode/theme-mode-selector.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { userPrefersMode, setMode } from 'mode-watcher';
import { m } from '#lib/paraglide/messages.js';
import { SunIcon, MoonIcon, MonitorIcon } from '#lib/icons/index.js';
@@ -26,10 +28,16 @@
async function selectMode(value: 'light' | 'dark' | 'system') {
setMode(value);
if (!$userStore) return;
- try {
- const updated = await userService.updateMyProfile({ preferences: { themeMode: value } });
- await userStore.setUser(updated);
- } catch (err) {
+
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const updated = await userService.updateMyProfile({ preferences: { themeMode: value } });
+ await userStore.setUser(updated);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const err = operationResult1.error;
+
console.error('Failed to save theme mode', err);
}
}
diff --git a/frontend/src/lib/components/ui/image-cropper/image-cropper-state.svelte.ts b/frontend/src/lib/components/ui/image-cropper/image-cropper-state.svelte.ts
index dc8158645..24fc5fb87 100644
--- a/frontend/src/lib/components/ui/image-cropper/image-cropper-state.svelte.ts
+++ b/frontend/src/lib/components/ui/image-cropper/image-cropper-state.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { ReadableBoxedValues, WritableBoxedValues } from 'svelte-toolbelt';
import { Context } from 'runed';
import type { CropArea, DispatchEvents } from 'svelte-easy-crop';
@@ -48,11 +49,17 @@ class ImageCropperRootState {
async onCrop() {
if (!this.pixelCrop || !this.tempUrl) return;
- try {
- this.opts.src.current = await getCroppedImg(this.tempUrl, this.pixelCrop);
- this.open = false;
- this.opts.onCropped.current(this.opts.src.current);
- } catch (error) {
+ const { tempUrl, pixelCrop } = this;
+ const operationResult1 = await tryCatch(
+ (async () => {
+ this.opts.src.current = await getCroppedImg(tempUrl, pixelCrop);
+ this.open = false;
+ this.opts.onCropped.current(this.opts.src.current);
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
this.opts.onError.current(error instanceof Error ? error : new Error('failed to crop image'));
}
}
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
index 12caf9a2c..c1b068550 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -126,30 +128,37 @@
if (isScanning) return;
try {
- const result = await scanMutation.mutateAsync();
- if (result) {
- lastScanRequestedAt = result.scanTime || nowInstantString();
- const summary: VulnerabilityScanSummary = {
- imageId: result.imageId,
- scanTime: result.scanTime,
- status: result.status,
- activityId: result.activityId,
- scanPhase: result.scanPhase,
- summary: result.summary,
- error: result.error
- };
- scanSummary = summary;
- onScanned?.(summary);
- if (isVulnerabilityScanInProgress(result.status) && pollingEnabled) {
- toastVulnerabilityScanStatus(result, { includeStarted: true });
- beginPolling(true);
- } else {
- toastVulnerabilityScanStatus(result);
- }
+ const operationResult1 = await tryCatch(
+ (async () => {
+ const result = await scanMutation.mutateAsync();
+ if (result) {
+ lastScanRequestedAt = result.scanTime || nowInstantString();
+ const summary: VulnerabilityScanSummary = {
+ imageId: result.imageId,
+ scanTime: result.scanTime,
+ status: result.status,
+ activityId: result.activityId,
+ scanPhase: result.scanPhase,
+ summary: result.summary,
+ error: result.error
+ };
+ scanSummary = summary;
+ onScanned?.(summary);
+ if (isVulnerabilityScanInProgress(result.status) && pollingEnabled) {
+ toastVulnerabilityScanStatus(result, { includeStarted: true });
+ beginPolling(true);
+ } else {
+ toastVulnerabilityScanStatus(result);
+ }
+ }
+ })()
+ );
+ if (operationResult1.error !== null) {
+ const error = operationResult1.error;
+
+ console.error('Error scanning image:', error);
+ toast.error(m.vuln_scan_failed());
}
- } catch (error) {
- console.error('Error scanning image:', error);
- toast.error(m.vuln_scan_failed());
} finally {
// no-op, TanStack manages pending state
}
@@ -179,19 +188,23 @@
},
onComplete: async (summary) => {
let resolvedSummary = summary;
- try {
- resolvedSummary = await stabilizeFailedVulnerabilitySummary(
- imageId,
- summary,
- (id) =>
- queryClient.fetchQuery({
- queryKey: queryKeys.vulnerabilities.summaryByImage(id),
- queryFn: () => vulnerabilityService.getScanSummary(id),
- staleTime: 0
- }),
- { scanRequestedAt: lastScanRequestedAt ?? scanSummary?.scanTime }
- );
- } catch {
+
+ const operationResult2 = await tryCatch(
+ (async () => {
+ resolvedSummary = await stabilizeFailedVulnerabilitySummary(
+ imageId,
+ summary,
+ (id) =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.vulnerabilities.summaryByImage(id),
+ queryFn: () => vulnerabilityService.getScanSummary(id),
+ staleTime: 0
+ }),
+ { scanRequestedAt: lastScanRequestedAt ?? scanSummary?.scanTime }
+ );
+ })()
+ );
+ if (operationResult2.error !== null) {
// Keep original summary when stabilization check fails.
}
diff --git a/frontend/src/lib/hooks/use-backup-activity.svelte.ts b/frontend/src/lib/hooks/use-backup-activity.svelte.ts
index 941ff407e..b98cd2151 100644
--- a/frontend/src/lib/hooks/use-backup-activity.svelte.ts
+++ b/frontend/src/lib/hooks/use-backup-activity.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { untrack } from 'svelte';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -51,7 +52,14 @@ export function useBackupActivity(
$effect(() => {
if (!activeQuery.dataUpdatedAt) return;
untrack(() => {
- void onChange().catch((error) => console.warn('Failed to refresh backup history', error));
+ void tryCatch(onChange()).then((result) => {
+ if (result.error !== null) {
+ const error = result.error;
+ return console.warn('Failed to refresh backup history', error);
+ } else {
+ return result.data;
+ }
+ });
});
});
diff --git a/frontend/src/lib/hooks/use-category-search.svelte.ts b/frontend/src/lib/hooks/use-category-search.svelte.ts
index e6476870f..6e7666ce8 100644
--- a/frontend/src/lib/hooks/use-category-search.svelte.ts
+++ b/frontend/src/lib/hooks/use-category-search.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { debounced } from '#lib/utils/ws.js';
type CategorySearchResponse<T> = {
@@ -33,13 +34,17 @@ export function useCategorySearch<T>({ search, filter, onError }: UseCategorySea
isSearching = true;
showSearchResults = true;
- try {
- const response = await search(trimmedQuery);
- if (requestId === currentSearchRequest) {
- searchResults = (response.results || []).filter(filter);
- isSearching = false;
- }
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await search(trimmedQuery);
+ if (requestId === currentSearchRequest) {
+ searchResults = (response.results || []).filter(filter);
+ isSearching = false;
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
onError?.(error);
if (requestId === currentSearchRequest) {
searchResults = [];
diff --git a/frontend/src/lib/hooks/use-clipboard.svelte.ts b/frontend/src/lib/hooks/use-clipboard.svelte.ts
index a51aa19f1..823bc66ae 100644
--- a/frontend/src/lib/hooks/use-clipboard.svelte.ts
+++ b/frontend/src/lib/hooks/use-clipboard.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
/*
Installed from @ieedan/shadcn-svelte-extras
*/
@@ -54,15 +55,18 @@ export class UseClipboard {
clearTimeout(this.timeout);
}
- try {
- await navigator.clipboard.writeText(text);
+ const operationResult = await tryCatch(
+ (async () => {
+ await navigator.clipboard.writeText(text);
- this.#copiedStatus = 'success';
+ this.#copiedStatus = 'success';
- this.timeout = setTimeout(() => {
- this.#copiedStatus = undefined;
- }, this.delay);
- } catch {
+ this.timeout = setTimeout(() => {
+ this.#copiedStatus = undefined;
+ }, this.delay);
+ })()
+ );
+ if (operationResult.error !== null) {
// an error can occur when not in the browser or if the user hasn't given clipboard access
this.#copiedStatus = 'failure';
diff --git a/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts b/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts
index 03e7b056f..b47566a95 100644
--- a/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts
+++ b/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { swarmService } from '#lib/services/swarm-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { SwarmJoinCandidate } from '#lib/types/swarm.js';
@@ -16,14 +17,17 @@ export function useEasyJoinCandidates() {
const currentRequest = ++requestVersion;
if (!environmentId) return;
- void swarmService
- .getSwarmJoinCandidates(environmentId)
- .then((result) => {
+ void tryCatch(
+ swarmService.getSwarmJoinCandidates(environmentId).then((result) => {
if (currentRequest === requestVersion) candidates = result;
})
- .catch(() => {
+ ).then((result) => {
+ if (result.error !== null) {
if (currentRequest === requestVersion) candidates = [];
- });
+ } else {
+ return result.data;
+ }
+ });
});
return {
diff --git a/frontend/src/lib/hooks/use-settings-form.svelte.ts b/frontend/src/lib/hooks/use-settings-form.svelte.ts
index a71707a17..a016ac023 100644
--- a/frontend/src/lib/hooks/use-settings-form.svelte.ts
+++ b/frontend/src/lib/hooks/use-settings-form.svelte.ts
@@ -2,7 +2,7 @@ import { getContext } from 'svelte';
import settingsStore from '#lib/stores/config-store.js';
import { settingsService } from '#lib/services/settings-service.js';
import type { Settings } from '#lib/types/settings.js';
-import { tryCatch } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { Readable } from 'svelte/store';
type SettingsFormState = {
diff --git a/frontend/src/lib/hooks/use-url-tab.svelte.ts b/frontend/src/lib/hooks/use-url-tab.svelte.ts
index 1cd712baa..e2f87952e 100644
--- a/frontend/src/lib/hooks/use-url-tab.svelte.ts
+++ b/frontend/src/lib/hooks/use-url-tab.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { onMount, untrack } from 'svelte';
@@ -24,8 +25,14 @@ export function useUrlTab<T extends string>({
function updateUrl(url: URL) {
const state = page.state;
- pendingUrlUpdate = pendingUrlUpdate
- .catch(() => undefined)
+ pendingUrlUpdate = tryCatch(pendingUrlUpdate)
+ .then((result) => {
+ if (result.error !== null) {
+ return undefined;
+ } else {
+ return result.data;
+ }
+ })
.then(() =>
goto(url, {
replace: true,
diff --git a/frontend/src/lib/services/api-service.ts b/frontend/src/lib/services/api-service.ts
index fe795371d..c37203796 100644
--- a/frontend/src/lib/services/api-service.ts
+++ b/frontend/src/lib/services/api-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { m } from '#lib/paraglide/messages.js';
import ky, { HTTPError as KyHTTPError, NetworkError, TimeoutError, type Options as KyOptions, type SearchParamsOption } from 'ky';
import { toast } from 'svelte-sonner';
@@ -259,20 +260,27 @@ export async function handleUnauthorizedResponseInternal(
const recoverable = isVersionMismatch || upgradeInProgressInternal;
if (!tokenRefreshHandler) return 'none';
- try {
- await tokenRefreshHandler();
- if (!isVersionMismatch || !upgradeInProgressInternal) return 'retry';
- if (!upgradeReloadStartedInternal) {
- upgradeReloadStartedInternal = true;
- window.location.reload();
- }
- return 'reload';
- } catch (error) {
+
+ const operationResult = await tryCatch(
+ (async () => {
+ await tokenRefreshHandler();
+ if (!isVersionMismatch || !upgradeInProgressInternal) return 'retry';
+ if (!upgradeReloadStartedInternal) {
+ upgradeReloadStartedInternal = true;
+ window.location.reload();
+ }
+ return 'reload';
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
const isTransientRefreshFailure =
error instanceof APIError && (error.name === 'NetworkError' || error.name === 'TimeoutError');
if (recoverable && isTransientRefreshFailure) return 'none';
window.location.replace(`/login?redirect=${encodeURIComponent(pathname)}`);
return 'redirect';
+ } else {
+ return operationResult.data;
}
}
@@ -335,18 +343,23 @@ class APIClient {
url
};
- try {
- const options = buildRequestOptionsInternal(method, data, config);
-
- const response = await this.client(requestUrl, options);
- const parsed = method.toUpperCase() === 'HEAD' ? undefined : await parseResponseBody(response.clone(), config.responseType);
- return {
- data: parsed as T,
- headers: response.headers,
- raw: response,
- status: response.status
- };
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const options = buildRequestOptionsInternal(method, data, config);
+
+ const response = await this.client(requestUrl, options);
+ const parsed =
+ method.toUpperCase() === 'HEAD' ? undefined : await parseResponseBody(response.clone(), config.responseType);
+ return {
+ data: parsed as T,
+ headers: response.headers,
+ raw: response,
+ status: response.status
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
if (error instanceof KyHTTPError) {
return this.handleHttpError<T>(error, method, url, data, config, requestConfig, requestUrl);
}
@@ -383,6 +396,8 @@ class APIClient {
config: requestConfig,
requestUrl
});
+ } else {
+ return operationResult.data;
}
}
diff --git a/frontend/src/lib/services/api/system-upgrade-service.ts b/frontend/src/lib/services/api/system-upgrade-service.ts
index d29b6d763..cb61870da 100644
--- a/frontend/src/lib/services/api/system-upgrade-service.ts
+++ b/frontend/src/lib/services/api/system-upgrade-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { apiClient } from '../api-service';
import type { AppVersionInformation } from '#lib/types/settings.js';
@@ -107,14 +108,19 @@ async function getUpdateAllStatus(): Promise<UpdateAllJob> {
* @returns Promise with health check result
*/
async function checkHealth(environmentId: string = '0'): Promise<HealthCheckResult> {
- try {
- const endpoint = environmentId === '0' ? '/health' : `/environments/${environmentId}/system/health`;
- const res = await apiClient.head(endpoint, {
- timeout: 3000
- });
- return { healthy: res.status === 200 };
- } catch {
+ const operationResult = await tryCatch(
+ (async () => {
+ const endpoint = environmentId === '0' ? '/health' : `/environments/${environmentId}/system/health`;
+ const res = await apiClient.head(endpoint, {
+ timeout: 3000
+ });
+ return { healthy: res.status === 200 };
+ })()
+ );
+ if (operationResult.error !== null) {
return { healthy: false };
+ } else {
+ return operationResult.data;
}
}
diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.ts
index b31ae996a..2fbecddad 100644
--- a/frontend/src/lib/services/auth-service.ts
+++ b/frontend/src/lib/services/auth-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { goto, refreshAll } from '$app/navigation';
import BaseAPIService, { APIError } from './api-service';
import userStore from '#lib/stores/user-store.js';
@@ -81,8 +82,14 @@ class AuthService extends BaseAPIService {
if (refreshTime > 0) {
this.refreshTimer = setTimeout(() => {
- this.refreshAccessToken().catch((err) => {
- console.error('Background token refresh failed:', err);
+ tryCatch(this.refreshAccessToken()).then((result) => {
+ if (result.error !== null) {
+ const err = result.error;
+
+ console.error('Background token refresh failed:', err);
+ } else {
+ return result.data;
+ }
});
}, refreshTime);
}
@@ -105,24 +112,28 @@ class AuthService extends BaseAPIService {
this.isRefreshing = true;
- try {
- const response = await this.handleResponse<{
- token?: string;
- refreshToken?: string;
- expiresAt?: string;
- }>(this.api.post('/auth/refresh', { refreshToken }));
-
- if (response.refreshToken && response.expiresAt) {
- this.storeTokenData(response.refreshToken, response.expiresAt);
- }
-
- const token = response.token || null;
- this.refreshSubscribers.forEach((callback) => callback(token));
- this.refreshSubscribers = [];
- this.isRefreshing = false;
-
- return token;
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await this.handleResponse<{
+ token?: string;
+ refreshToken?: string;
+ expiresAt?: string;
+ }>(this.api.post('/auth/refresh', { refreshToken }));
+
+ if (response.refreshToken && response.expiresAt) {
+ this.storeTokenData(response.refreshToken, response.expiresAt);
+ }
+
+ const token = response.token || null;
+ this.refreshSubscribers.forEach((callback) => callback(token));
+ this.refreshSubscribers = [];
+ this.isRefreshing = false;
+
+ return token;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
const err = error instanceof Error ? error : new Error('Token refresh failed');
console.error('Token refresh failed:', err);
// Only drop the stored refresh token when the server definitively rejects it
@@ -135,6 +146,8 @@ class AuthService extends BaseAPIService {
this.refreshSubscribers = [];
this.isRefreshing = false;
throw err;
+ } else {
+ return operationResult.data;
}
}
@@ -168,16 +181,21 @@ class AuthService extends BaseAPIService {
}
async getCurrentUser(): Promise<User | null> {
- try {
- const response = await this.api.get('/auth/me');
- const user = (response.data.user as User) || (response.data.data as User);
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await this.api.get('/auth/me');
+ const user = (response.data.user as User) || (response.data.data as User);
- userStore.setUser(user);
+ userStore.setUser(user);
- return user;
- } catch {
+ return user;
+ })()
+ );
+ if (operationResult.error !== null) {
userStore.clearUser();
return null;
+ } else {
+ return operationResult.data;
}
}
@@ -229,13 +247,9 @@ class AuthService extends BaseAPIService {
* @returns The auto-login config, or null if the request fails
*/
async getAutoLoginConfig(): Promise<AutoLoginConfig | null> {
- try {
- const response = await this.handleResponse<AutoLoginConfig>(this.api.get('/auth/auto-login-config'));
- return response;
- } catch {
- // Silently fail - auto-login is optional
- return null;
- }
+ const result = await tryCatch(this.handleResponse<AutoLoginConfig>(this.api.get('/auth/auto-login-config')));
+ // Silently fail - auto-login is optional.
+ return result.data;
}
/**
@@ -244,14 +258,10 @@ class AuthService extends BaseAPIService {
* @returns The user if login succeeded, null otherwise
*/
async attemptAutoLogin(): Promise<User | null> {
- try {
- const data = await this.handleResponse<AuthenticationResponse>(this.api.post('/auth/auto-login'));
- if (data.status === 'mfa_required') return null;
- return this.completeAuthentication(data);
- } catch {
- // Silently fail - fall back to normal login flow
- return null;
- }
+ const result = await tryCatch(this.handleResponse<AuthenticationResponse>(this.api.post('/auth/auto-login')));
+ // Silently fail - fall back to normal login flow.
+ if (result.error !== null || result.data.status === 'mfa_required') return null;
+ return this.completeAuthentication(result.data);
}
}
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index eb864009f..9c1c10779 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import BaseAPIService from './api-service';
import { uploadService, type UploadProgressCallback } from './upload-service';
import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte.js';
@@ -105,41 +106,55 @@ class ImageService extends BaseAPIService {
async pullImageStream(imageName: string, onLine?: (data: any) => void): Promise<ImagePullResult> {
const envId = await environmentStore.getCurrentEnvironmentId();
- try {
- const response = await fetch(`/api/environments/${envId}/images/pull`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ imageName })
- });
-
- if (!response.ok || !response.body) {
- const errorData = await response.json().catch(() => ({
- data: { message: m.images_pull_server_error() }
- }));
- const errorMessage =
- errorData.data?.message ||
- errorData.error ||
- errorData.message ||
- `${m.images_pull_server_error()}: HTTP ${response.status}`;
- throw new Error(errorMessage);
- }
-
- await readNdjsonStream(response.body, (parsed) => {
- onLine?.(parsed);
- if (parsed?.error) {
- const message = typeof parsed.error === 'string' ? parsed.error : parsed.error.message || m.images_pull_stream_failed();
- throw new Error(message);
+
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await fetch(`/api/environments/${envId}/images/pull`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ imageName })
+ });
+
+ if (!response.ok || !response.body) {
+ const errorData = await tryCatch(response.json()).then((result) => {
+ if (result.error !== null) {
+ return {
+ data: { message: m.images_pull_server_error() }
+ };
+ } else {
+ return result.data;
+ }
+ });
+ const errorMessage =
+ errorData.data?.message ||
+ errorData.error ||
+ errorData.message ||
+ `${m.images_pull_server_error()}: HTTP ${response.status}`;
+ throw new Error(errorMessage);
}
- // The terminal frame marks success; don't wait on the network EOF.
- return parsed?.done === true;
- });
- return { success: true, imageName };
- } catch (error) {
+
+ await readNdjsonStream(response.body, (parsed) => {
+ onLine?.(parsed);
+ if (parsed?.error) {
+ const message =
+ typeof parsed.error === 'string' ? parsed.error : parsed.error.message || m.images_pull_stream_failed();
+ throw new Error(message);
+ }
+ // The terminal frame marks success; don't wait on the network EOF.
+ return parsed?.done === true;
+ });
+ return { success: true, imageName };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
return {
success: false,
imageName,
error: error instanceof Error ? error.message : m.images_pull_stream_failed()
};
+ } else {
+ return operationResult.data;
}
}
diff --git a/frontend/src/lib/services/stream-service.ts b/frontend/src/lib/services/stream-service.ts
index 9a05e4898..1499f34c3 100644
--- a/frontend/src/lib/services/stream-service.ts
+++ b/frontend/src/lib/services/stream-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import BaseAPIService, { handleUnauthorizedResponseInternal } from './api-service';
import { streamCacheBuster } from '#lib/utils/streaming.js';
@@ -29,7 +30,7 @@ class StreamService extends BaseAPIService {
if (response.status === 401) {
// Nothing reads this body, so release its connection before deciding
// what to do next.
- await response.body?.cancel().catch(() => {});
+ if (response.body) await tryCatch(response.body.cancel());
const action = await handleUnauthorizedResponseInternal('/stream', retry);
if (action === 'retry') {
return this.openClientStream(signal, channels, params, true);
diff --git a/frontend/src/lib/services/upload-service.ts b/frontend/src/lib/services/upload-service.ts
index cc260e171..d6cc9858b 100644
--- a/frontend/src/lib/services/upload-service.ts
+++ b/frontend/src/lib/services/upload-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import BaseAPIService from './api-service';
export type UploadKind = 'image' | 'volume-backup' | 'build-workspace';
@@ -70,24 +71,26 @@ class UploadService extends BaseAPIService {
const chunk = file.slice(start, Math.min(start + session.chunkSize, file.size));
for (let attempt = 1; ; attempt++) {
- try {
- const updated = await this.putChunk(envId, kind, session.id, index, chunk);
- received = new Set(updated.receivedChunks);
- break;
- } catch (error) {
- if (attempt >= chunkRetryAttempts) {
- await this.deleteSession(envId, kind, session.id).catch(() => {});
- throw error;
- }
- await new Promise((resolve) => setTimeout(resolve, chunkRetryDelayMs * attempt));
- // Resume: skip anything the server already has.
- try {
- received = new Set((await this.getSession(envId, kind, session.id)).receivedChunks);
- if (received.has(index)) break;
- } catch {
- // The status check is best-effort; keep retrying the chunk.
- }
+ const chunkResult = await tryCatch(
+ (async () => {
+ const updated = await this.putChunk(envId, kind, session.id, index, chunk);
+ received = new Set(updated.receivedChunks);
+ })()
+ );
+ if (chunkResult.error === null) break;
+ if (attempt >= chunkRetryAttempts) {
+ await tryCatch(this.deleteSession(envId, kind, session.id));
+ throw chunkResult.error;
}
+ await new Promise((resolve) => setTimeout(resolve, chunkRetryDelayMs * attempt));
+ // The status check is best-effort; resume anything the server already has.
+ const statusResult = await tryCatch(
+ (async () => {
+ received = new Set((await this.getSession(envId, kind, session.id)).receivedChunks);
+ return received.has(index);
+ })()
+ );
+ if (statusResult.data) break;
}
report();
}
diff --git a/frontend/src/lib/services/version-service.ts b/frontend/src/lib/services/version-service.ts
index 4021f1ac6..efb0038e2 100644
--- a/frontend/src/lib/services/version-service.ts
+++ b/frontend/src/lib/services/version-service.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { version as currentVersion } from '$app/env';
import { apiClient } from './api-service';
import type { AppVersionInformation } from '#lib/types/settings.js';
@@ -7,33 +8,36 @@ function getCurrentVersion() {
}
async function getVersionInformation(): Promise<AppVersionInformation> {
- try {
- const res = await apiClient.get('/app-version', {
- timeout: 2000
- });
- const data = res.data as Partial<AppVersionInformation>;
+ const operationResult = await tryCatch(
+ (async () => {
+ const res = await apiClient.get('/app-version', {
+ timeout: 2000
+ });
+ const data = res.data as Partial<AppVersionInformation>;
- return {
- currentVersion: data.currentVersion || getCurrentVersion(),
- currentTag: data.currentTag,
- currentDigest: data.currentDigest,
- displayVersion: data.displayVersion || data.currentVersion || getCurrentVersion(),
- revision: data.revision || 'unknown',
- shortRevision: data.shortRevision || data.revision?.slice(0, 8) || 'unknown',
- goVersion: data.goVersion || 'unknown',
- nodeVersion: data.nodeVersion || 'unknown',
- svelteKitVersion: data.svelteKitVersion || 'unknown',
- enabledFeatures: data.enabledFeatures ?? [],
- buildTime: data.buildTime,
- isSemverVersion: data.isSemverVersion || false,
- newestVersion: data.newestVersion,
- newestDigest: data.newestDigest,
- updateAvailable: data.updateAvailable || false,
- releaseUrl: data.releaseUrl,
- releaseNotes: data.releaseNotes,
- releasedAt: data.releasedAt
- };
- } catch (error) {
+ return {
+ currentVersion: data.currentVersion || getCurrentVersion(),
+ currentTag: data.currentTag,
+ currentDigest: data.currentDigest,
+ displayVersion: data.displayVersion || data.currentVersion || getCurrentVersion(),
+ revision: data.revision || 'unknown',
+ shortRevision: data.shortRevision || data.revision?.slice(0, 8) || 'unknown',
+ goVersion: data.goVersion || 'unknown',
+ nodeVersion: data.nodeVersion || 'unknown',
+ svelteKitVersion: data.svelteKitVersion || 'unknown',
+ enabledFeatures: data.enabledFeatures ?? [],
+ buildTime: data.buildTime,
+ isSemverVersion: data.isSemverVersion || false,
+ newestVersion: data.newestVersion,
+ newestDigest: data.newestDigest,
+ updateAvailable: data.updateAvailable || false,
+ releaseUrl: data.releaseUrl,
+ releaseNotes: data.releaseNotes,
+ releasedAt: data.releasedAt
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
// Fallback to basic version info if app-version endpoint fails
return {
currentVersion: getCurrentVersion(),
@@ -47,6 +51,8 @@ async function getVersionInformation(): Promise<AppVersionInformation> {
isSemverVersion: false,
updateAvailable: false
};
+ } else {
+ return operationResult.data;
}
}
diff --git a/frontend/src/lib/stores/activity.store.svelte.ts b/frontend/src/lib/stores/activity.store.svelte.ts
index dd34e8c17..7ba7a2196 100644
--- a/frontend/src/lib/stores/activity.store.svelte.ts
+++ b/frontend/src/lib/stores/activity.store.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { activityService } from '#lib/services/activity-service.js';
import { STREAM_CHANNEL_ACTIVITIES } from '#lib/services/stream-service.js';
import { LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte.js';
@@ -225,21 +226,28 @@ function createActivityStore() {
...state,
loading: true
}));
- try {
- const result = await activityService.getActivities(
- { pagination: { page: 1, limit: ACTIVITY_LIST_LIMIT } },
- environmentId
- );
- // The environment can be removed while the fetch is in-flight; don't resurrect it.
- if (!core.isCurrentGeneration(generation) || !core.environmentState(environmentId)) {
- return;
- }
- replaceEnvironmentSnapshotInternal(environmentId, result.data ?? []);
- } catch (error) {
+
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await activityService.getActivities(
+ { pagination: { page: 1, limit: ACTIVITY_LIST_LIMIT } },
+ environmentId
+ );
+ // The environment can be removed while the fetch is in-flight; don't resurrect it.
+ if (!core.isCurrentGeneration(generation) || !core.environmentState(environmentId)) {
+ return;
+ }
+ replaceEnvironmentSnapshotInternal(environmentId, result.data ?? []);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
if (core.isCurrentGeneration(generation) && core.environmentState(environmentId)) {
console.warn('Failed to refresh activities:', error);
core.setEnvironmentError(environmentId, error);
}
+ } else {
+ return operationResult.data;
}
},
onEnvironmentRemoved(environmentId) {
@@ -397,29 +405,37 @@ function createActivityStore() {
const generation = sessionGeneration;
_detailLoadingIds = { ..._detailLoadingIds, [activityId]: true };
try {
- const detail = await activityService.getActivity(
- activityId,
- activityEnvironmentIdInternal(activityId),
- ACTIVITY_DETAIL_LIMIT
+ const operationResult = await tryCatch(
+ (async () => {
+ const detail = await activityService.getActivity(
+ activityId,
+ activityEnvironmentIdInternal(activityId),
+ ACTIVITY_DETAIL_LIMIT
+ );
+ if (generation !== sessionGeneration) {
+ return;
+ }
+ const environmentId = sourceEnvironmentIdInternal(detail.activity);
+ const normalized = {
+ ...detail,
+ activity: normalizeActivityInternal(detail.activity, environmentId)
+ };
+ _details = { ..._details, [activityId]: normalized };
+ const nextErrors = { ..._detailErrorIds };
+ delete nextErrors[activityId];
+ _detailErrorIds = nextErrors;
+ })()
);
- if (generation !== sessionGeneration) {
- return;
- }
- const environmentId = sourceEnvironmentIdInternal(detail.activity);
- const normalized = {
- ...detail,
- activity: normalizeActivityInternal(detail.activity, environmentId)
- };
- _details = { ..._details, [activityId]: normalized };
- const nextErrors = { ..._detailErrorIds };
- delete nextErrors[activityId];
- _detailErrorIds = nextErrors;
- } catch (error) {
- if (generation !== sessionGeneration) {
- return;
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ if (generation !== sessionGeneration) {
+ return;
+ }
+ console.warn('Failed to load activity detail:', error);
+ _detailErrorIds = { ..._detailErrorIds, [activityId]: true };
+ } else {
+ return operationResult.data;
}
- console.warn('Failed to load activity detail:', error);
- _detailErrorIds = { ..._detailErrorIds, [activityId]: true };
} finally {
if (generation === sessionGeneration) {
const next = { ..._detailLoadingIds };
@@ -629,11 +645,15 @@ function createActivityStore() {
const states = Object.values(core.environmentStates);
await Promise.all(
states.map(async (state) => {
- try {
- const result = await activityService.clearHistory(state.id);
- deleted += result.deleted ?? 0;
- succeeded += 1;
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await activityService.clearHistory(state.id);
+ deleted += result.deleted ?? 0;
+ succeeded += 1;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
failed.push({
environmentId: state.id,
environmentName: state.name,
diff --git a/frontend/src/lib/stores/dashboard.store.svelte.ts b/frontend/src/lib/stores/dashboard.store.svelte.ts
index 3b540a825..b13946e84 100644
--- a/frontend/src/lib/stores/dashboard.store.svelte.ts
+++ b/frontend/src/lib/stores/dashboard.store.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { browser } from '$app/env';
import { dashboardService } from '#lib/services/dashboard-service.js';
import { STREAM_CHANNEL_DASHBOARD } from '#lib/services/stream-service.js';
@@ -60,18 +61,24 @@ function createDashboardStore() {
}
},
async fetchSnapshot(environmentId, generation) {
- try {
- const snapshot = await dashboardService.getDashboardForEnvironment(environmentId, { debugAllGood });
- // The environment can be removed while the fetch is in-flight; don't resurrect it.
- if (!core.isCurrentGeneration(generation) || !core.environmentState(environmentId)) {
- return;
- }
- replaceEnvironmentSnapshotInternal(environmentId, snapshot);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const snapshot = await dashboardService.getDashboardForEnvironment(environmentId, { debugAllGood });
+ // The environment can be removed while the fetch is in-flight; don't resurrect it.
+ if (!core.isCurrentGeneration(generation) || !core.environmentState(environmentId)) {
+ return;
+ }
+ replaceEnvironmentSnapshotInternal(environmentId, snapshot);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
if (core.isCurrentGeneration(generation) && core.environmentState(environmentId)) {
console.warn('Failed to refresh dashboard snapshot:', error);
core.setEnvironmentError(environmentId, error, { errorCode: undefined });
}
+ } else {
+ return operationResult.data;
}
}
});
diff --git a/frontend/src/lib/stores/json-line-stream.svelte.ts b/frontend/src/lib/stores/json-line-stream.svelte.ts
index f6b8d5471..3c98e97cf 100644
--- a/frontend/src/lib/stores/json-line-stream.svelte.ts
+++ b/frontend/src/lib/stores/json-line-stream.svelte.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { browser } from '$app/env';
const MAX_RECONNECT_DELAY = 15_000;
@@ -97,26 +98,34 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
const controller = new AbortController();
streamAbortController = controller;
try {
- const response = await config.openStream(controller.signal);
- if (!isCurrentGeneration(generation) || !response.body) {
- // The response body is live even though nobody will read it;
- // dropping it on the floor leaves the server streaming into a
- // connection that stays open until its TCP timers expire.
- controller.abort();
- if (streamAbortController === controller) {
- streamAbortController = null;
- }
- return;
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await config.openStream(controller.signal);
+ if (!isCurrentGeneration(generation) || !response.body) {
+ // The response body is live even though nobody will read it;
+ // dropping it on the floor leaves the server streaming into a
+ // connection that stays open until its TCP timers expire.
+ controller.abort();
+ if (streamAbortController === controller) {
+ streamAbortController = null;
+ }
+ return;
+ }
- _streamConnected = true;
- _streamFailed = false;
- reconnectAttempt = 0;
- config.onConnected?.();
- await readJSONLines(response.body, generation);
- } catch (error) {
- if (!controller.signal.aborted && isCurrentGeneration(generation)) {
- console.warn(`${config.label} stream disconnected:`, error);
+ _streamConnected = true;
+ _streamFailed = false;
+ reconnectAttempt = 0;
+ config.onConnected?.();
+ await readJSONLines(response.body, generation);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ if (!controller.signal.aborted && isCurrentGeneration(generation)) {
+ console.warn(`${config.label} stream disconnected:`, error);
+ }
+ } else {
+ return operationResult.data;
}
} finally {
if (streamAbortController === controller) {
@@ -162,7 +171,7 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
// The loop also exits when the generation advances, with the stream
// still open. Cancelling is what actually closes the fetch and lets
// the server see the disconnect; releaseLock alone does not.
- await reader.cancel().catch(() => {});
+ await tryCatch(reader.cancel());
reader.releaseLock();
}
}
diff --git a/frontend/src/lib/types/result.ts b/frontend/src/lib/types/result.ts
new file mode 100644
index 000000000..b26926a9d
--- /dev/null
+++ b/frontend/src/lib/types/result.ts
@@ -0,0 +1,11 @@
+type Success<T> = {
+ data: T;
+ error: null;
+};
+
+type Failure<E> = {
+ data: null;
+ error: E;
+};
+
+export type Result<T, E = Error> = Success<T> | Failure<E>;
diff --git a/frontend/src/lib/utils/api.ts b/frontend/src/lib/utils/api.ts
index dfa1b3cb8..66771602e 100644
--- a/frontend/src/lib/utils/api.ts
+++ b/frontend/src/lib/utils/api.ts
@@ -2,28 +2,8 @@ import { error as kitError } from '@sveltejs/kit';
import { toast } from 'svelte-sonner';
import { APIError, extractServerMessage } from '#lib/services/api-service.js';
-// --- Result wrapper ---
-
-type Success<T> = {
- data: T;
- error: null;
-};
-
-type Failure<E> = {
- data: null;
- error: E;
-};
-
-export type Result<T, E = Error> = Success<T> | Failure<E>;
-
-export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
- try {
- const data = await promise;
- return { data, error: null };
- } catch (error) {
- return { data: null, error: error as E };
- }
-}
+import type { Result } from '#lib/types/result.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
// --- API error extraction ---
@@ -155,7 +135,7 @@ export async function parallelRefresh<T extends Record<string, RefreshTask<any>>
const task = tasks[key as keyof T];
if (!task) return;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(task.fetch()),
message: task.errorMessage,
setLoadingState: (value) => updateLoading(key, value),
@@ -173,11 +153,17 @@ export async function simpleRefresh<T>(
): Promise<void> {
setLoading(true);
try {
- const data = await fetch();
- onSuccess(data);
- } catch (error) {
- console.error('Refresh failed:', error);
- toast.error(errorMessage);
+ const operationResult = await tryCatch(
+ (async () => {
+ const data = await fetch();
+ onSuccess(data);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Refresh failed:', error);
+ toast.error(errorMessage);
+ }
} finally {
setLoading(false);
}
diff --git a/frontend/src/lib/utils/bulk-actions.ts b/frontend/src/lib/utils/bulk-actions.ts
index 5cb4c19f9..01179790c 100644
--- a/frontend/src/lib/utils/bulk-actions.ts
+++ b/frontend/src/lib/utils/bulk-actions.ts
@@ -3,7 +3,9 @@ import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { streamCacheBuster } from '#lib/utils/streaming.js';
import { markActivityToastShown } from '#lib/components/activity/activity-completion-toasts.js';
import { runWithActivityBatchId } from '#lib/services/api-service.js';
-import { handleApiResultWithCallbacks, tryCatch, type Result } from '#lib/utils/api.js';
+import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
+import type { Result } from '#lib/types/result.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
/**
diff --git a/frontend/src/lib/utils/compose-flow.ts b/frontend/src/lib/utils/compose-flow.ts
index 300b6c54d..4c39ebd56 100644
--- a/frontend/src/lib/utils/compose-flow.ts
+++ b/frontend/src/lib/utils/compose-flow.ts
@@ -2,7 +2,8 @@ import { arcaneButtonVariants, actionConfigs } from '#lib/components/arcane-butt
import { m } from '#lib/paraglide/messages.js';
import { templateService } from '#lib/services/template-service.js';
import type { Template } from '#lib/types/swarm.js';
-import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import { parseDocument } from 'yaml';
import { z } from 'zod/v4';
@@ -175,7 +176,8 @@ async function createComposeTemplate({ validate, setLoading, beforeValidate }: C
const { name, composeContent, envContent } = validated;
- handleApiResultWithCallbacks({
+ setLoading(true);
+ await handleApiResultWithCallbacks({
result: await tryCatch(
templateService.createTemplate({
name,
@@ -201,8 +203,9 @@ export async function submitComposeResourceForm<TResult>({
const validated = validate();
if (!validated) return;
- handleApiResultWithCallbacks({
- result: await tryCatch(submit(validated)),
+ setLoading(true);
+ await handleApiResultWithCallbacks({
+ result: await tryCatch((async () => await submit(validated))()),
message: failureMessage(validated.name),
setLoadingState: setLoading,
onSuccess: async (result) => {
diff --git a/frontend/src/lib/utils/container-actions.ts b/frontend/src/lib/utils/container-actions.ts
index 813988513..36f6f6e22 100644
--- a/frontend/src/lib/utils/container-actions.ts
+++ b/frontend/src/lib/utils/container-actions.ts
@@ -1,7 +1,8 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { m } from '#lib/paraglide/messages.js';
import { containerService } from '#lib/services/container-service.js';
-import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { toast } from 'svelte-sonner';
@@ -67,19 +68,23 @@ export async function runContainerLifecycleAction({
const config = containerLifecycleActionConfigs[action];
setStatus(config.status);
- try {
- handleApiResultWithCallbacks({
- result: await tryCatch(config.run(containerId)),
- message: config.failure(),
- setLoadingState: (value) => {
- setStatus(value ? config.status : '');
- },
- async onSuccess(data) {
- toast.success(config.success(), activityToastOptions(extractActivityId(data)));
- await onRefresh?.();
- }
- });
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(config.run(containerId)),
+ message: config.failure(),
+ setLoadingState: (value) => {
+ setStatus(value ? config.status : '');
+ },
+ async onSuccess(data) {
+ toast.success(config.success(), activityToastOptions(extractActivityId(data)));
+ await onRefresh?.();
+ }
+ });
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
console.error('Container action failed:', error);
toast.error(m.containers_action_error());
setStatus('');
@@ -113,7 +118,7 @@ export function confirmAndRemoveContainer({
const force = !!checkboxStates['force'];
const volumes = !!checkboxStates['volumes'];
setStatus('removing');
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(containerService.deleteContainer(containerId, { force, volumes })),
message: m.containers_remove_failed(),
setLoadingState: (value) => {
@@ -166,29 +171,35 @@ export function confirmAndUpdateContainer({
action: async () => {
setLoading?.(true);
try {
- if (showPullingToast) {
- toast.info(m.containers_update_pulling_image());
+ const operationResult = await tryCatch(
+ (async () => {
+ if (showPullingToast) {
+ toast.info(m.containers_update_pulling_image());
+ }
+
+ const result = (await containerService.updateContainer(containerId)) as ContainerUpdateResult;
+ const toastOptions = useActivityToast ? activityToastOptions(extractActivityId(result)) : undefined;
+
+ if ((result.failed ?? 0) > 0) {
+ const failedItem = result.items?.find((item) => item.status === 'failed');
+ toast.error(
+ m.containers_update_failed({ name: containerName }) + (failedItem?.error ? `: ${failedItem.error}` : ''),
+ toastOptions
+ );
+ } else if ((result.updated ?? 0) > 0) {
+ toast.success(m.containers_update_success({ name: containerName }), toastOptions);
+ } else {
+ toast.info(m.image_update_up_to_date_title(), toastOptions);
+ }
+
+ await onRefresh?.();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Container update failed:', error);
+ toast.error(m.containers_update_failed({ name: containerName }));
}
-
- const result = (await containerService.updateContainer(containerId)) as ContainerUpdateResult;
- const toastOptions = useActivityToast ? activityToastOptions(extractActivityId(result)) : undefined;
-
- if ((result.failed ?? 0) > 0) {
- const failedItem = result.items?.find((item) => item.status === 'failed');
- toast.error(
- m.containers_update_failed({ name: containerName }) + (failedItem?.error ? `: ${failedItem.error}` : ''),
- toastOptions
- );
- } else if ((result.updated ?? 0) > 0) {
- toast.success(m.containers_update_success({ name: containerName }), toastOptions);
- } else {
- toast.info(m.image_update_up_to_date_title(), toastOptions);
- }
-
- await onRefresh?.();
- } catch (error) {
- console.error('Container update failed:', error);
- toast.error(m.containers_update_failed({ name: containerName }));
} finally {
setLoading?.(false);
}
diff --git a/frontend/src/lib/utils/docker.ts b/frontend/src/lib/utils/docker.ts
index a9b7eeee2..243182caa 100644
--- a/frontend/src/lib/utils/docker.ts
+++ b/frontend/src/lib/utils/docker.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { m } from '#lib/paraglide/messages.js';
import type { ContainerStats, ContainerSummaryDto } from '#lib/types/docker.js';
import type { Environment, EnvironmentStatus } from '#lib/types/environment.js';
@@ -298,17 +299,19 @@ export function startVulnerabilityScanPolling(
const run = async () => {
if (cancelled) return;
attempts += 1;
- try {
- const summary = await fetchSummary(imageId);
- onUpdate?.(summary);
-
- const isScanning = isVulnerabilityScanInProgress(summary?.status);
- if (!isScanning) {
- onComplete?.(summary);
- return;
- }
- } catch (error) {
- onError?.(error);
+ const result = await tryCatch(
+ (async () => {
+ const summary = await fetchSummary(imageId);
+ onUpdate?.(summary);
+ const isScanning = isVulnerabilityScanInProgress(summary?.status);
+ if (!isScanning) onComplete?.(summary);
+ return isScanning;
+ })()
+ );
+ if (result.error !== null) {
+ onError?.(result.error);
+ } else if (!result.data) {
+ return;
}
if (maxAttempts > 0 && attempts >= maxAttempts) {
diff --git a/frontend/src/lib/utils/formatting.ts b/frontend/src/lib/utils/formatting.ts
index 1a24d2821..8f05550eb 100644
--- a/frontend/src/lib/utils/formatting.ts
+++ b/frontend/src/lib/utils/formatting.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import Convert from 'ansi-to-html';
import { Temporal } from 'temporal-polyfill';
import { z } from 'zod/v4';
@@ -373,10 +374,14 @@ export function formatElapsedTime(value: InstantInput, options: RelativeTimeForm
}
export async function setLocale(locale: Locale, reload = true) {
- try {
- const zodLocale = await import(`../../../node_modules/zod/v4/locales/${locale}.js`);
- z.config(zodLocale.default());
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const zodLocale = await import(`../../../node_modules/zod/v4/locales/${locale}.js`);
+ z.config(zodLocale.default());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
console.warn(`Failed to load zod locale for ${locale}:`, error);
}
diff --git a/frontend/src/lib/utils/settings-form.ts b/frontend/src/lib/utils/settings-form.ts
index 29192adcb..663781eb2 100644
--- a/frontend/src/lib/utils/settings-form.ts
+++ b/frontend/src/lib/utils/settings-form.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import { z } from 'zod/v4';
import { UseSettingsForm } from '#lib/hooks/use-settings-form.svelte.js';
@@ -52,13 +53,19 @@ export function createSettingsForm<T extends z.ZodType<any, any>>(config: Settin
settingsForm.setLoading(true);
try {
- await settingsForm.updateSettings(data);
- toast.success(successMessage);
- onSuccess?.();
- } catch (error) {
- console.error('Failed to save settings:', error);
- const message = error instanceof Error ? error.message : errorMessage;
- toast.error(message);
+ const operationResult = await tryCatch(
+ (async () => {
+ await settingsForm.updateSettings(data);
+ toast.success(successMessage);
+ onSuccess?.();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Failed to save settings:', error);
+ const message = error instanceof Error ? error.message : errorMessage;
+ toast.error(message);
+ }
} finally {
settingsForm.setLoading(false);
}
diff --git a/frontend/src/lib/utils/settings-load.ts b/frontend/src/lib/utils/settings-load.ts
index a53ede536..a8b75d697 100644
--- a/frontend/src/lib/utils/settings-load.ts
+++ b/frontend/src/lib/utils/settings-load.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { settingsService } from '#lib/services/settings-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
@@ -16,14 +17,20 @@ export async function loadMergedSettingsPage(parent: ParentWithQueryClient, erro
const client = queryClient as QueryClientLike;
const envId = await environmentStore.getCurrentEnvironmentId();
- try {
- const settings = await client.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- });
- return { settings };
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const settings = await client.fetchQuery({
+ queryKey: queryKeys.settings.byEnvironment(envId),
+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
+ });
+ return { settings };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
console.error(`Failed to load ${errorContext}:`, error);
throw error;
+ } else {
+ return operationResult.data;
}
}
diff --git a/frontend/src/lib/utils/streaming.ts b/frontend/src/lib/utils/streaming.ts
index a63f5ccd5..16075f9ee 100644
--- a/frontend/src/lib/utils/streaming.ts
+++ b/frontend/src/lib/utils/streaming.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { Temporal } from 'temporal-polyfill';
/**
@@ -54,7 +55,7 @@ export async function readNdjsonStream(
const stopFromLine = onLine?.(obj) === true;
const stopFromMessage = onMessage?.(obj) === true;
if (stopFromLine || stopFromMessage) {
- await reader.cancel().catch(() => {});
+ await tryCatch(reader.cancel());
return;
}
}
diff --git a/frontend/src/lib/utils/template-editor.ts b/frontend/src/lib/utils/template-editor.ts
index aa577199b..a4f8db58d 100644
--- a/frontend/src/lib/utils/template-editor.ts
+++ b/frontend/src/lib/utils/template-editor.ts
@@ -1,5 +1,6 @@
import { m } from '#lib/paraglide/messages.js';
-import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import { z } from 'zod/v4';
@@ -103,8 +104,9 @@ export async function runTemplateEditorSave<TValidated, TResult>({
const validated = validateTemplateEditorForm(validationState, validate);
if (!validated) return;
- handleApiResultWithCallbacks({
- result: await tryCatch(save(validated)),
+ setLoading(true);
+ await handleApiResultWithCallbacks({
+ result: await tryCatch((async () => await save(validated))()),
message: failureMessage,
setLoadingState: setLoading,
onSuccess: async (result) => {
diff --git a/frontend/src/lib/utils/template-load.ts b/frontend/src/lib/utils/template-load.ts
index fa505c788..bc94c9776 100644
--- a/frontend/src/lib/utils/template-load.ts
+++ b/frontend/src/lib/utils/template-load.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { templateService } from '#lib/services/template-service.js';
import { variableService } from '#lib/services/variable-service.js';
@@ -21,46 +22,70 @@ export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
const client = queryClient as QueryClientLike;
const [defaultTemplates, templates, globalVariables] = await Promise.all([
- client
- .fetchQuery({
+ tryCatch(
+ client.fetchQuery({
queryKey: queryKeys.templates.defaults(),
queryFn: () => templateService.getDefaultTemplates()
})
- .catch((err) => {
+ ).then((result) => {
+ if (result.error !== null) {
+ const err = result.error;
+
console.warn('Failed to load default templates:', err);
return { composeTemplate: '', envTemplate: '' };
- }),
- client
- .fetchQuery({
+ } else {
+ return result.data;
+ }
+ }),
+ tryCatch(
+ client.fetchQuery({
queryKey: queryKeys.templates.allTemplates(),
queryFn: () => templateService.getAllTemplates()
})
- .catch((err) => {
+ ).then((result) => {
+ if (result.error !== null) {
+ const err = result.error;
+
console.warn('Failed to load templates:', err);
return [];
- }),
- client
- .fetchQuery({
+ } else {
+ return result.data;
+ }
+ }),
+ tryCatch(
+ client.fetchQuery({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
- .catch((err) => {
+ ).then((result) => {
+ if (result.error !== null) {
+ const err = result.error;
+
console.warn('Failed to load global variables:', err);
return [];
- })
+ } else {
+ return result.data;
+ }
+ })
]);
return { defaultTemplates, templates, globalVariables };
}
export async function loadTemplateContent(client: QueryClientLike, templateId: string) {
- return client
- .fetchQuery({
+ return tryCatch(
+ client.fetchQuery({
queryKey: queryKeys.templates.content(templateId),
queryFn: () => templateService.getTemplateContent(templateId)
})
- .catch((err) => {
+ ).then((result) => {
+ if (result.error !== null) {
+ const err = result.error;
+
console.warn('Failed to load selected template:', err);
return null;
- });
+ } else {
+ return result.data;
+ }
+ });
}
diff --git a/frontend/src/lib/utils/try-catch.ts b/frontend/src/lib/utils/try-catch.ts
new file mode 100644
index 000000000..76da6cee8
--- /dev/null
+++ b/frontend/src/lib/utils/try-catch.ts
@@ -0,0 +1,10 @@
+import type { Result } from '#lib/types/result.js';
+
+export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
+ try {
+ const data = await promise;
+ return { data, error: null };
+ } catch (error) {
+ return { data: null, error: error as E };
+ }
+}
diff --git a/frontend/src/lib/utils/update-actions.ts b/frontend/src/lib/utils/update-actions.ts
index 01980ce41..79ae06a7d 100644
--- a/frontend/src/lib/utils/update-actions.ts
+++ b/frontend/src/lib/utils/update-actions.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -81,13 +82,9 @@ const SELF_UPGRADE_MAX_WAIT_MS = 5 * 60 * 1000;
async function disarmWhenBackendResponds() {
const deadline = Date.now() + SELF_UPGRADE_MAX_WAIT_MS;
for (;;) {
- try {
- await userService.getCurrentUser();
- break;
- } catch {
- if (Date.now() >= deadline) break;
- await new Promise((resolve) => setTimeout(resolve, SELF_UPGRADE_PROBE_INTERVAL_MS));
- }
+ const result = await tryCatch(userService.getCurrentUser());
+ if (result.error === null || Date.now() >= deadline) break;
+ await new Promise((resolve) => setTimeout(resolve, SELF_UPGRADE_PROBE_INTERVAL_MS));
}
BaseAPIService.setUpgradeInProgress(false);
}
@@ -113,11 +110,17 @@ export function confirmAndApplyAllUpdates({ setLoading, onRefresh }: ConfirmAndA
const restartsThisBackend = envId === MANAGER_ENVIRONMENT_ID;
if (restartsThisBackend) BaseAPIService.setUpgradeInProgress(true);
try {
- summarizeUpdateResult(await imageService.runAutoUpdate());
- await onRefresh?.();
- } catch (error) {
- console.error('Update all failed:', error);
- toast.error(m.updates_apply_all_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ summarizeUpdateResult(await imageService.runAutoUpdate());
+ await onRefresh?.();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Update all failed:', error);
+ toast.error(m.updates_apply_all_failed());
+ }
} finally {
if (restartsThisBackend) void disarmWhenBackendResponds();
setLoading?.(false);
diff --git a/frontend/src/lib/utils/workspace-files.ts b/frontend/src/lib/utils/workspace-files.ts
index 97ca84d66..c83a3c675 100644
--- a/frontend/src/lib/utils/workspace-files.ts
+++ b/frontend/src/lib/utils/workspace-files.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { CodeLanguage } from '#lib/components/code-editor/analysis/types.js';
import { m } from '#lib/paraglide/messages.js';
import { toast } from 'svelte-sonner';
@@ -200,12 +201,18 @@ export async function readWorkspaceUpload(
maxFileSizeMb: number
): Promise<{ content?: string; binary: boolean; error?: string }> {
if (file.size > maxFileSizeMb * 1024 * 1024) return { binary: false, error: m.workspace_upload_too_large({ maxFileSizeMb }) };
- try {
- const bytes = new Uint8Array(await file.arrayBuffer());
- if (bytes.includes(0)) return { binary: true };
- return { binary: false, content: new TextDecoder('utf-8', { fatal: true }).decode(bytes) };
- } catch {
+
+ const operationResult = await tryCatch(
+ (async () => {
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ if (bytes.includes(0)) return { binary: true };
+ return { binary: false, content: new TextDecoder('utf-8', { fatal: true }).decode(bytes) };
+ })()
+ );
+ if (operationResult.error !== null) {
return { binary: true };
+ } else {
+ return operationResult.data;
}
}
diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.ts
index 71853d490..328c47c4c 100644
--- a/frontend/src/lib/utils/ws.ts
+++ b/frontend/src/lib/utils/ws.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { SystemStats } from '#lib/types/shared.js';
import type { Diagnostics, LogEntry } from '#lib/types/diagnostics.js';
@@ -48,15 +49,14 @@ export class ReconnectingWebSocket<T = unknown> {
}
this.connecting = true;
- let url: string;
- try {
- url = await this.opts.buildUrl();
- } catch (err) {
+ const urlResult = await tryCatch((async () => await this.opts.buildUrl())());
+ if (urlResult.error !== null) {
this.connecting = false;
this.scheduleReconnect();
- this.opts.onError?.(err as Error);
+ this.opts.onError?.(urlResult.error);
return;
}
+ const url = urlResult.data;
let socket: WebSocket;
try {
diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelte
index 96025ee66..f619352ab 100644
--- a/frontend/src/routes/(app)/account/+page.svelte
+++ b/frontend/src/routes/(app)/account/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { fromStore } from 'svelte/store';
import { toast } from 'svelte-sonner';
import HeaderCard from '#lib/components/header-card.svelte';
@@ -93,15 +95,18 @@
avatarUrl = getDefaultProfilePicture();
return;
}
- try {
- const encoder = new TextEncoder();
- const data = encoder.encode(email.toLowerCase().trim());
- const hashBuffer = await crypto.subtle.digest('SHA-256', data);
- const hash = Array.from(new Uint8Array(hashBuffer))
- .map((b) => b.toString(16).padStart(2, '0'))
- .join('');
- avatarUrl = `https://www.gravatar.com/avatar/${hash}?s=128&d=404`;
- } catch {
+ const operationResult = await tryCatch(
+ (async () => {
+ const encoder = new TextEncoder();
+ const data = encoder.encode(email.toLowerCase().trim());
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
+ const hash = Array.from(new Uint8Array(hashBuffer))
+ .map((b) => b.toString(16).padStart(2, '0'))
+ .join('');
+ avatarUrl = `https://www.gravatar.com/avatar/${hash}?s=128&d=404`;
+ })()
+ );
+ if (operationResult.error !== null) {
avatarUrl = getDefaultProfilePicture();
}
}
@@ -110,15 +115,22 @@
if (!currentUser || !profileDirty || profileSaving) return;
profileSaving = true;
try {
- const updated = await userService.updateMyProfile({
- displayName: profileDisplayName.trim(),
- email: profileEmail.trim()
- });
- await userStore.setUser(updated);
- toast.success(m.account_profile_updated());
- } catch (err) {
- const msg = err instanceof Error ? err.message : m.common_update_failed({ resource: m.account_profile_title() });
- toast.error(msg);
+ const operationResult = await tryCatch(
+ (async () => {
+ const updated = await userService.updateMyProfile({
+ displayName: profileDisplayName.trim(),
+ email: profileEmail.trim()
+ });
+ await userStore.setUser(updated);
+ toast.success(m.account_profile_updated());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ const msg = err instanceof Error ? err.message : m.common_update_failed({ resource: m.account_profile_title() });
+ toast.error(msg);
+ }
} finally {
profileSaving = false;
}
@@ -132,18 +144,24 @@
async function handleCroppedAvatar(url: string) {
avatarUploading = true;
try {
- const preparedFile = await prepareAvatarUploadFile(url, avatarMaxUploadSizeBytes, ImageCropper.getFileFromUrl);
- if (!preparedFile.ok) {
- toast.error(m.account_avatar_size_error({ maxSizeMb: avatarMaxUploadSizeMb }));
- return;
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ const preparedFile = await prepareAvatarUploadFile(url, avatarMaxUploadSizeBytes, ImageCropper.getFileFromUrl);
+ if (!preparedFile.ok) {
+ toast.error(m.account_avatar_size_error({ maxSizeMb: avatarMaxUploadSizeMb }));
+ return;
+ }
- const updatedUser = await userService.uploadMyAvatar(preparedFile.file);
- await userStore.setUser(updatedUser);
- avatarCacheBuster = Temporal.Now.instant().epochMilliseconds;
- toast.success(m.account_avatar_upload_success());
- } catch (err) {
- toast.error(err instanceof Error ? err.message : m.account_avatar_upload_failed());
+ const updatedUser = await userService.uploadMyAvatar(preparedFile.file);
+ await userStore.setUser(updatedUser);
+ avatarCacheBuster = Temporal.Now.instant().epochMilliseconds;
+ toast.success(m.account_avatar_upload_success());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+ toast.error(err instanceof Error ? err.message : m.account_avatar_upload_failed());
+ }
} finally {
avatarUploading = false;
URL.revokeObjectURL(url);
@@ -163,12 +181,19 @@
if (!currentUser?.avatarUrl) return;
avatarUploading = true;
try {
- const updatedUser = await userService.deleteMyAvatar();
- await userStore.setUser(updatedUser);
- avatarCacheBuster = Temporal.Now.instant().epochMilliseconds;
- toast.success(m.account_avatar_remove_success());
- } catch (err) {
- toast.error(err instanceof Error ? err.message : m.account_avatar_remove_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const updatedUser = await userService.deleteMyAvatar();
+ await userStore.setUser(updatedUser);
+ avatarCacheBuster = Temporal.Now.instant().epochMilliseconds;
+ toast.success(m.account_avatar_remove_success());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ toast.error(err instanceof Error ? err.message : m.account_avatar_remove_failed());
+ }
} finally {
avatarUploading = false;
}
diff --git a/frontend/src/routes/(app)/account/account-api-keys-panel.svelte b/frontend/src/routes/(app)/account/account-api-keys-panel.svelte
index c0686d297..c1485bc53 100644
--- a/frontend/src/routes/(app)/account/account-api-keys-panel.svelte
+++ b/frontend/src/routes/(app)/account/account-api-keys-panel.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import ApiKeyFormSheet from '#lib/components/sheets/api-key-form-sheet.svelte';
@@ -20,9 +22,14 @@
async function loadApiKeys() {
apiKeysLoading = true;
try {
- apiKeys = await apiKeyService.listMine();
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.common_refresh_failed({ resource: m.api_key_page_title() }));
+ const operationResult = await tryCatch((async () => apiKeyService.listMine())());
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_refresh_failed({ resource: m.api_key_page_title() }));
+ } else {
+ apiKeys = operationResult.data;
+ }
} finally {
apiKeysLoading = false;
}
@@ -37,16 +44,23 @@
}) {
creatingKey = true;
try {
- const payload: CreateUserApiKey = {
- name: apiKey.name,
- description: apiKey.description,
- expiresAt: apiKey.expiresAt
- };
- createdKey = await apiKeyService.createMine(payload);
- showCreateKeyForm = false;
- await loadApiKeys();
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.api_key_create_failed({ name: apiKey.name }));
+ const operationResult = await tryCatch(
+ (async () => {
+ const payload: CreateUserApiKey = {
+ name: apiKey.name,
+ description: apiKey.description,
+ expiresAt: apiKey.expiresAt
+ };
+ createdKey = await apiKeyService.createMine(payload);
+ showCreateKeyForm = false;
+ await loadApiKeys();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.api_key_create_failed({ name: apiKey.name }));
+ }
} finally {
creatingKey = false;
}
diff --git a/frontend/src/routes/(app)/account/account-preferences-panel.svelte b/frontend/src/routes/(app)/account/account-preferences-panel.svelte
index 3b3393d75..5d77f4b93 100644
--- a/frontend/src/routes/(app)/account/account-preferences-panel.svelte
+++ b/frontend/src/routes/(app)/account/account-preferences-panel.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { mode } from 'mode-watcher';
import ThemeModeSelector from '#lib/components/theme-mode/theme-mode-selector.svelte';
import LocalePicker from '#lib/components/locale-picker.svelte';
@@ -56,10 +58,15 @@
async function savePreferences(patch: Partial<UserPreferences>) {
const previous = currentUser;
if (!previous) return;
- try {
- const updated = await userService.updateMyProfile({ preferences: patch });
- await userStore.setUser(updated);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const updated = await userService.updateMyProfile({ preferences: patch });
+ await userStore.setUser(updated);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.account_preferences() }));
await userStore.setUser(previous);
}
diff --git a/frontend/src/routes/(app)/account/account-security-panel.svelte b/frontend/src/routes/(app)/account/account-security-panel.svelte
index 82a57580d..5e8e7123a 100644
--- a/frontend/src/routes/(app)/account/account-security-panel.svelte
+++ b/frontend/src/routes/(app)/account/account-security-panel.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { fromStore } from 'svelte/store';
import { toast } from 'svelte-sonner';
import PasskeySettings from '#lib/components/auth/passkey-settings.svelte';
@@ -26,13 +28,20 @@
if (!passwordValid || passwordSaving) return;
passwordSaving = true;
try {
- await userService.changePassword({ currentPassword, newPassword });
- toast.success(m.account_password_updated());
- currentPassword = '';
- newPassword = '';
- confirmPassword = '';
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.common_password() }));
+ const operationResult = await tryCatch(
+ (async () => {
+ await userService.changePassword({ currentPassword, newPassword });
+ toast.success(m.account_password_updated());
+ currentPassword = '';
+ newPassword = '';
+ confirmPassword = '';
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.common_password() }));
+ }
} finally {
passwordSaving = false;
}
@@ -42,10 +51,17 @@
if (revokingAll) return;
revokingAll = true;
try {
- await userService.logoutAllOtherSessions();
- toast.success(m.account_sessions_signed_out());
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.common_action_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ await userService.logoutAllOtherSessions();
+ toast.success(m.account_sessions_signed_out());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_action_failed());
+ }
} finally {
revokingAll = false;
}
diff --git a/frontend/src/routes/(app)/containers/+page.ts b/frontend/src/routes/(app)/containers/+page.ts
index c1cc29614..0831a4cab 100644
--- a/frontend/src/routes/(app)/containers/+page.ts
+++ b/frontend/src/routes/(app)/containers/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { containerService } from '#lib/services/container-service.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
@@ -16,13 +17,19 @@ export const load: PageLoad = async ({ parent }) => {
} satisfies SearchPaginationSortRequest);
let containers;
- try {
- containers = await queryClient.fetchQuery({
- queryKey: queryKeys.containers.list(envId, containerRequestOptions),
- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.containers.list(envId, containerRequestOptions),
+ queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load containers');
+ } else {
+ containers = operationResult.data;
}
return {
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index 831ed5a7f..91b91b28c 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton, type ArcaneButtonSize } from '#lib/components/arcane-button/index.js';
import { goto, refreshAll } from '$app/navigation';
import settingsStore from '#lib/stores/config-store.js';
@@ -166,14 +168,18 @@
}
// A slower lookup for a previous image must not overwrite the current one.
let current = true;
- imageService
- .getUpdateInfoByRefs([image])
- .then((infoByRef) => {
+ tryCatch(
+ imageService.getUpdateInfoByRefs([image]).then((infoByRef) => {
if (current) updateInfo = infoByRef[image] ?? null;
})
- .catch(() => {
+ ).then((result) => {
+ if (result.error) {
if (current) updateInfo = null;
- });
+
+ return;
+ }
+ return result.data;
+ });
return () => {
current = false;
};
@@ -262,21 +268,24 @@
const includes = proj.includeFiles ?? [];
if (includes.length === 0) return null;
- const envId = await environmentStore.getCurrentEnvironmentId().catch(() => null);
+ const envId = await tryCatch(environmentStore.getCurrentEnvironmentId()).then((result) =>
+ result.error ? null : result.data
+ );
if (!envId) return null;
for (const f of includes) {
if (f.content && hasServiceInContent(f.content, svcName)) {
return { includeFile: f };
}
- try {
- const loaded = await projectWorkspaceService.getWorkspaceFile(proj.id, f.relativePath, envId);
- if (loaded?.content && hasServiceInContent(loaded.content, svcName)) {
- return { includeFile: { ...f, content: loaded.content } };
- }
- } catch {
- // Skip files that fail to load
- }
+ const sourceResult = await tryCatch(
+ (async () => {
+ const loaded = await projectWorkspaceService.getWorkspaceFile(proj.id, f.relativePath, envId);
+ if (loaded?.content && hasServiceInContent(loaded.content, svcName)) {
+ return { includeFile: { ...f, content: loaded.content } };
+ }
+ })()
+ );
+ if (sourceResult.error === null && sourceResult.data) return sourceResult.data;
}
return null;
}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
index f76e7062c..5ed86879b 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.ts
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import { containerService } from '#lib/services/container-service.js';
@@ -11,56 +12,71 @@ export const load: PageLoad = async ({ params, parent }) => {
const envId = await environmentStore.getCurrentEnvironmentId();
const containerId = params.containerId;
- try {
- const [container, settings] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.containers.detail(envId, containerId),
- queryFn: () => containerService.getContainerForEnvironment(envId, containerId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- })
- ]);
+ const operationResult = await tryCatch(
+ (async () => {
+ const [container, settings] = await Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.containers.detail(envId, containerId),
+ queryFn: () => containerService.getContainerForEnvironment(envId, containerId)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.settings.byEnvironment(envId),
+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
+ })
+ ]);
- if (!container) {
- throw error(404, 'Container not found');
- }
+ if (!container) {
+ throw error(404, 'Container not found');
+ }
+
+ let project = null;
+ const composeProjectName = container.composeInfo?.projectName;
+ if (composeProjectName) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const searchOptions = {
+ search: composeProjectName,
+ pagination: { page: 1, limit: 100 } // Ensure we don't miss projects beyond default page size
+ };
+ const projectsResult = await queryClient.fetchQuery({
+ queryKey: queryKeys.projects.list(envId, searchOptions),
+ queryFn: () => projectService.getProjectsForEnvironment(envId, searchOptions)
+ });
+ const matched = projectsResult.data.find((p) => p.name === composeProjectName);
+ if (matched) {
+ return await queryClient.fetchQuery({
+ queryKey: queryKeys.projects.detail(envId, matched.id),
+ queryFn: () => projectService.getProjectForEnvironment(envId, matched.id)
+ });
+ }
+ return null;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- let project = null;
- const composeProjectName = container.composeInfo?.projectName;
- if (composeProjectName) {
- try {
- const searchOptions = {
- search: composeProjectName,
- pagination: { page: 1, limit: 100 } // Ensure we don't miss projects beyond default page size
- };
- const projectsResult = await queryClient.fetchQuery({
- queryKey: queryKeys.projects.list(envId, searchOptions),
- queryFn: () => projectService.getProjectsForEnvironment(envId, searchOptions)
- });
- const matched = projectsResult.data.find((p) => p.name === composeProjectName);
- if (matched) {
- project = await queryClient.fetchQuery({
- queryKey: queryKeys.projects.detail(envId, matched.id),
- queryFn: () => projectService.getProjectForEnvironment(envId, matched.id)
- });
+ console.warn('Failed to load compose project:', err);
+ } else {
+ project = operationResult.data;
}
- } catch (err) {
- console.warn('Failed to load compose project:', err);
}
- }
- return {
- container,
- settings,
- project
- };
- } catch (err: unknown) {
+ return {
+ container,
+ settings,
+ project
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err: unknown = operationResult.error;
+
console.error('Failed to load container:', err);
if (typeof err === 'object' && err !== null && 'status' in err && (err as { status: number }).status === 404) {
throw err;
}
throw error(500, err instanceof Error ? err.message : 'Failed to load container details');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte b/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte
index 69cb0c6be..15a1f0912 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Card from '#lib/components/ui/card/index.js';
import { PortBadge } from '#lib/components/badges/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -15,7 +17,7 @@
import { createQuery } from '@tanstack/svelte-query';
import { refreshAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
- import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
interface Props {
container: ContainerDetailsDto;
@@ -52,22 +54,25 @@
if (!connectNetwork) return;
connectPending = true;
try {
- const aliases = connectAliases
- .split(',')
- .map((alias) => alias.trim())
- .filter(Boolean);
- await networkService.connectContainer(connectNetwork, {
- containerId: container.id,
- aliases: aliases.length > 0 ? aliases : undefined,
- ipv4Address: connectIp.trim() || undefined
- });
- toast.success(m.network_connect_success());
- connectNetwork = '';
- connectAliases = '';
- connectIp = '';
- await refreshAll();
- } catch (error) {
- toast.error(m.network_connect_failed(), { description: extractApiErrorMessage(error) });
+ const operationResult = await tryCatch(
+ (async () => {
+ const aliases = connectAliases
+ .split(',')
+ .map((alias) => alias.trim())
+ .filter(Boolean);
+ await networkService.connectContainer(connectNetwork, {
+ containerId: container.id,
+ aliases: aliases.length > 0 ? aliases : undefined,
+ ipv4Address: connectIp.trim() || undefined
+ });
+ toast.success(m.network_connect_success());
+ connectNetwork = '';
+ connectAliases = '';
+ connectIp = '';
+ await refreshAll();
+ })()
+ );
+ await handleApiResultWithCallbacks({ result: operationResult, message: m.network_connect_failed() });
} finally {
connectPending = false;
}
@@ -83,11 +88,14 @@
action: async () => {
disconnectPending[networkName] = true;
try {
- await networkService.disconnectContainer(networkId || networkName, { containerId: container.id, force: false });
- toast.success(m.network_disconnect_success());
- await refreshAll();
- } catch (error) {
- toast.error(m.network_disconnect_failed(), { description: extractApiErrorMessage(error) });
+ const operationResult = await tryCatch(
+ (async () => {
+ await networkService.disconnectContainer(networkId || networkName, { containerId: container.id, force: false });
+ toast.success(m.network_disconnect_success());
+ await refreshAll();
+ })()
+ );
+ await handleApiResultWithCallbacks({ result: operationResult, message: m.network_disconnect_failed() });
} finally {
disconnectPending[networkName] = false;
}
diff --git a/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte b/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
index 790800b71..a6d950f4b 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { Badge } from '#lib/components/ui/badge/index.js';
import { Switch } from '#lib/components/ui/switch/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -32,11 +34,16 @@
async function handleAutoUpdateToggle(checked: boolean) {
autoUpdateToggling = true;
try {
- await containerService.setAutoUpdate(container.id, checked);
- onAutoUpdateChange?.(checked);
- toast.success(checked ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
- } catch {
- toast.error(m.auto_update_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ await containerService.setAutoUpdate(container.id, checked);
+ onAutoUpdateChange?.(checked);
+ toast.success(checked ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
+ })()
+ );
+ if (operationResult.error !== null) {
+ toast.error(m.auto_update_failed());
+ }
} finally {
autoUpdateToggling = false;
}
diff --git a/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte b/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte
index 05fd7a4d5..c861b24ed 100644
--- a/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import * as Alert from '#lib/components/ui/alert/index.js';
@@ -53,20 +55,27 @@
isCommitting = true;
let didCommit = false;
try {
- const result = await containerService.commitContainer(containerId, {
- repository: data.repository.trim() || undefined,
- tag: data.tag?.trim() || undefined,
- comment: data.comment.trim() || undefined,
- author: data.author.trim() || undefined,
- noPause: data.noPause
- });
- toast.success(m.containers_commit_success({ imageId: result.id }));
- didCommit = true;
- open = false;
- onOpenChange?.(false);
- } catch (error) {
- console.error('Failed to commit container:', error);
- toast.error(m.containers_commit_failed({ name: containerName }));
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await containerService.commitContainer(containerId, {
+ repository: data.repository.trim() || undefined,
+ tag: data.tag?.trim() || undefined,
+ comment: data.comment.trim() || undefined,
+ author: data.author.trim() || undefined,
+ noPause: data.noPause
+ });
+ toast.success(m.containers_commit_success({ imageId: result.id }));
+ didCommit = true;
+ open = false;
+ onOpenChange?.(false);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Failed to commit container:', error);
+ toast.error(m.containers_commit_failed({ name: containerName }));
+ }
} finally {
isCommitting = false;
}
diff --git a/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte b/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte
index 95647fa16..f907f8455 100644
--- a/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { createContainerStatsWebSocket, type ReconnectingWebSocket } from '#lib/utils/ws.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ContainerStats as ContainerStatsType } from '#lib/types/docker.js';
@@ -30,38 +32,43 @@
hasInitialStatsLoaded = false;
isConnecting = true;
- try {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const operationResult = await tryCatch(
+ (async () => {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+
+ const ws = createContainerStatsWebSocket({
+ getEnvId: () => envId,
+ containerId,
+ onMessage: (statsData) => {
+ if (statsData.removed) {
+ void refreshAll();
+ return;
+ }
- const ws = createContainerStatsWebSocket({
- getEnvId: () => envId,
- containerId,
- onMessage: (statsData) => {
- if (statsData.removed) {
- void refreshAll();
- return;
- }
+ stats = statsData;
+ hasInitialStatsLoaded = true;
+ },
+ onOpen: () => {
+ isConnecting = false;
+ },
+ onError: (err) => {
+ console.error('Stats WebSocket error:', err);
+ isConnecting = false;
+ },
+ onClose: () => {
+ isConnecting = false;
+ },
+ maxBackoff: 5000,
+ shouldReconnect: () => enabled
+ });
- stats = statsData;
- hasInitialStatsLoaded = true;
- },
- onOpen: () => {
- isConnecting = false;
- },
- onError: (err) => {
- console.error('Stats WebSocket error:', err);
- isConnecting = false;
- },
- onClose: () => {
- isConnecting = false;
- },
- maxBackoff: 5000,
- shouldReconnect: () => enabled
- });
+ ws.connect();
+ statsWebSocket = ws;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- ws.connect();
- statsWebSocket = ws;
- } catch (error) {
console.error('Failed to connect to stats stream:', error);
isConnecting = false;
}
diff --git a/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte b/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte
index 9949e4a00..a02125a95 100644
--- a/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte
+++ b/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte
@@ -6,7 +6,8 @@
import { m } from '#lib/paraglide/messages.js';
import { toast } from 'svelte-sonner';
import { containerService } from '#lib/services/container-service.js';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
type Props = {
@@ -26,7 +27,7 @@
async function handleConfirm() {
if (!containerId) return;
isSubmitting = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(containerService.killContainer(containerId, signal)),
message: m.containers_kill_failed({ name: containerName }),
setLoadingState: (value) => {
diff --git a/frontend/src/routes/(app)/containers/container-table.actions.ts b/frontend/src/routes/(app)/containers/container-table.actions.ts
index 23b4f3eee..5eab565e6 100644
--- a/frontend/src/routes/(app)/containers/container-table.actions.ts
+++ b/frontend/src/routes/(app)/containers/container-table.actions.ts
@@ -4,7 +4,7 @@ import { m } from '#lib/paraglide/messages.js';
import { containerService, type ContainersPaginatedResponse } from '#lib/services/container-service.js';
import type { ContainerSummaryDto } from '#lib/types/docker.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
-import { tryCatch } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
import {
@@ -77,19 +77,24 @@ export function createContainerActions({
const config = containerActionConfigs[action];
actionStatus[id] = config.status;
- try {
- handleApiResultWithCallbacks({
- result: await tryCatch(config.run(id)),
- message: config.failure(),
- setLoadingState: (value) => {
- actionStatus[id] = value ? config.status : '';
- },
- async onSuccess(data) {
- toast.success(config.success(), activityToastOptions(extractActivityId(data)));
- await reloadContainers();
- }
- });
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(config.run(id)),
+ message: config.failure(),
+ setLoadingState: (value) => {
+ actionStatus[id] = value ? config.status : '';
+ },
+ async onSuccess(data) {
+ toast.success(config.success(), activityToastOptions(extractActivityId(data)));
+ await reloadContainers();
+ }
+ });
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Container action failed:', error);
toast.error(m.containers_action_error());
actionStatus[id] = '';
@@ -130,7 +135,7 @@ export function createContainerActions({
destructive: false,
action: async () => {
actionStatus[container.id] = 'redeploying';
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(containerService.redeployContainer(container.id)),
message: m.container_redeploy_failed(),
setLoadingState: (value) => {
diff --git a/frontend/src/routes/(app)/customize/+page.svelte b/frontend/src/routes/(app)/customize/+page.svelte
index 8fbb98d7f..897d9d8b1 100644
--- a/frontend/src/routes/(app)/customize/+page.svelte
+++ b/frontend/src/routes/(app)/customize/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import type { PageProps } from './$types';
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
@@ -57,12 +59,17 @@
}
onMount(async () => {
- try {
- customizeCategories = orderCategoriesByNav(
- (await customizeSearchService.getCategories()).filter(isAccessibleCategory),
- getCustomizeSubpageUrlsInNavOrder()
- );
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ customizeCategories = orderCategoriesByNav(
+ (await customizeSearchService.getCategories()).filter(isAccessibleCategory),
+ getCustomizeSubpageUrlsInNavOrder()
+ );
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to load categories:', error);
}
});
diff --git a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
index 664e1175e..cd0700048 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
+++ b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
@@ -4,7 +4,7 @@
import GitRepositoryFormSheet from '#lib/components/sheets/git-repository-sheet.svelte';
import RepositoryTable from './repository-table.svelte';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { m } from '#lib/paraglide/messages.js';
import { gitRepositoryService } from '#lib/services/git-repository-service.js';
import { ResourcePageLayout, type ActionButton } from '#lib/layouts/index.js';
@@ -26,7 +26,7 @@
async function refreshRepositories() {
isLoading.refresh = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(gitRepositoryService.getRepositories(requestOptions)),
message: m.common_refresh_failed({ resource: m.git_repositories_title() }),
setLoadingState: (value) => (isLoading.refresh = value),
@@ -56,19 +56,26 @@
isLoading[loadingKey] = true;
try {
- if (isEditMode && repositoryToEdit?.id) {
- await gitRepositoryService.updateRepository(repositoryToEdit.id, repository as GitRepositoryUpdateDto);
- toast.success(m.common_update_success({ resource: m.resource_repository() }));
- } else {
- await gitRepositoryService.createRepository(repository as GitRepositoryCreateDto);
- toast.success(m.common_create_success({ resource: m.resource_repository() }));
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ if (isEditMode && repositoryToEdit?.id) {
+ await gitRepositoryService.updateRepository(repositoryToEdit.id, repository as GitRepositoryUpdateDto);
+ toast.success(m.common_update_success({ resource: m.resource_repository() }));
+ } else {
+ await gitRepositoryService.createRepository(repository as GitRepositoryCreateDto);
+ toast.success(m.common_create_success({ resource: m.resource_repository() }));
+ }
+
+ repositories = await gitRepositoryService.getRepositories(requestOptions);
+ isRepositoryDialogOpen = false;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- repositories = await gitRepositoryService.getRepositories(requestOptions);
- isRepositoryDialogOpen = false;
- } catch (error) {
- console.error('Error saving repository:', error);
- toast.error(error instanceof Error ? error.message : m.common_save_failed());
+ console.error('Error saving repository:', error);
+ toast.error(error instanceof Error ? error.message : m.common_save_failed());
+ }
} finally {
isLoading[loadingKey] = false;
}
diff --git a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
index 9cfe2b8e3..c67893db6 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
+++ b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
@@ -6,7 +6,7 @@
import RemoveMenuItem from '#lib/components/arcane-table/cells/remove-menu-item.svelte';
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { GitRepository } from '#lib/types/automation.js';
import type { ColumnSpec, BulkAction } from '#lib/components/arcane-table/index.js';
@@ -112,7 +112,7 @@
isLoading.testing = true;
const safeName = name ?? m.common_unknown();
const result = await tryCatch(gitRepositoryService.testRepository(id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_test_failed({ resource: safeName }),
setLoadingState: () => {},
diff --git a/frontend/src/routes/(app)/customize/registries/+page.svelte b/frontend/src/routes/(app)/customize/registries/+page.svelte
index 19887325f..50e0e6502 100644
--- a/frontend/src/routes/(app)/customize/registries/+page.svelte
+++ b/frontend/src/routes/(app)/customize/registries/+page.svelte
@@ -6,7 +6,7 @@
import ContainerRegistryFormSheet from '#lib/components/sheets/container-registry-sheet.svelte';
import RegistryTable from './registry-table.svelte';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { m } from '#lib/paraglide/messages.js';
import { containerRegistryService } from '#lib/services/container-registry-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -40,7 +40,7 @@
async function refreshRegistries() {
isLoading.refresh = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(containerRegistryService.getRegistries(requestOptions)),
message: m.common_refresh_failed({ resource: m.registries_title() }),
setLoadingState: (value) => (isLoading.refresh = value),
@@ -71,19 +71,26 @@
isLoading[loadingKey] = true;
try {
- if (isEditMode && registryToEdit?.id) {
- await containerRegistryService.updateRegistry(registryToEdit.id, registry as ContainerRegistryUpdateDto);
- toast.success(m.common_update_success({ resource: m.resource_registry() }));
- } else {
- await containerRegistryService.createRegistry(registry as ContainerRegistryCreateDto);
- toast.success(m.common_create_success({ resource: m.resource_registry() }));
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ if (isEditMode && registryToEdit?.id) {
+ await containerRegistryService.updateRegistry(registryToEdit.id, registry as ContainerRegistryUpdateDto);
+ toast.success(m.common_update_success({ resource: m.resource_registry() }));
+ } else {
+ await containerRegistryService.createRegistry(registry as ContainerRegistryCreateDto);
+ toast.success(m.common_create_success({ resource: m.resource_registry() }));
+ }
+
+ [registries] = await Promise.all([containerRegistryService.getRegistries(requestOptions), pullUsageQuery.refetch()]);
+ isRegistryDialogOpen = false;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- [registries] = await Promise.all([containerRegistryService.getRegistries(requestOptions), pullUsageQuery.refetch()]);
- isRegistryDialogOpen = false;
- } catch (error) {
- console.error('Error saving registry:', error);
- toast.error(error instanceof Error ? error.message : m.registries_save_failed());
+ console.error('Error saving registry:', error);
+ toast.error(error instanceof Error ? error.message : m.registries_save_failed());
+ }
} finally {
isLoading[loadingKey] = false;
}
diff --git a/frontend/src/routes/(app)/customize/registries/+page.ts b/frontend/src/routes/(app)/customize/registries/+page.ts
index 10c70db1e..28811a253 100644
--- a/frontend/src/routes/(app)/customize/registries/+page.ts
+++ b/frontend/src/routes/(app)/customize/registries/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { containerRegistryService } from '#lib/services/container-registry-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -22,12 +23,12 @@ export const load: PageLoad = async ({ parent }) => {
queryKey: queryKeys.containerRegistries.list(registryRequestOptions),
queryFn: () => containerRegistryService.getRegistries(registryRequestOptions)
});
- const pullUsage = await queryClient
- .fetchQuery({
+ const pullUsage = await tryCatch(
+ queryClient.fetchQuery({
queryKey: queryKeys.containerRegistries.pullUsage(),
queryFn: () => containerRegistryService.getPullUsage()
})
- .catch(() => null);
+ ).then((result) => (result.error ? null : result.data));
return { registries, registryRequestOptions, pullUsage };
};
diff --git a/frontend/src/routes/(app)/customize/registries/registry-table.svelte b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
index dcde187d6..d0788ecd9 100644
--- a/frontend/src/routes/(app)/customize/registries/registry-table.svelte
+++ b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
@@ -4,7 +4,8 @@
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { toast } from 'svelte-sonner';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { ContainerRegistry, ContainerRegistryPullUsage } from '#lib/types/docker.js';
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table/index.js';
@@ -104,7 +105,7 @@
testingId = id;
const safeUrl = url ?? m.common_unknown();
const result = await tryCatch(containerRegistryService.testRegistry(id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.registries_test_failed({ url: safeUrl }),
setLoadingState: (value) => (value ? null : (testingId = null)),
diff --git a/frontend/src/routes/(app)/customize/templates/+page.svelte b/frontend/src/routes/(app)/customize/templates/+page.svelte
index 686c20cd7..d88889eec 100644
--- a/frontend/src/routes/(app)/customize/templates/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import AddTemplateRegistrySheet from '#lib/components/sheets/add-template-registry-sheet.svelte';
@@ -51,26 +53,32 @@
isLoading.updating[id] = true;
try {
- const registry = registries.find((r) => r.id === id);
- if (!registry) {
- toast.error(m.templates_registry_not_found());
- delete isLoading.updating[id];
- return;
+ const operationResult = await tryCatch(
+ (async () => {
+ const registry = registries.find((r) => r.id === id);
+ if (!registry) {
+ toast.error(m.templates_registry_not_found());
+ delete isLoading.updating[id];
+ return;
+ }
+
+ await templateService.updateRegistry(id, {
+ name: registry.name,
+ url: registry.url,
+ description: registry.description,
+ enabled: updates.enabled ?? registry.enabled
+ });
+
+ registries = await templateService.getRegistries();
+ templates = await templateService.getTemplates(requestOptions);
+ toast.success(m.common_update_success({ resource: m.resource_registry() }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Error updating registry:', error);
+ toast.error(error instanceof Error ? error.message : m.registries_save_failed());
}
-
- await templateService.updateRegistry(id, {
- name: registry.name,
- url: registry.url,
- description: registry.description,
- enabled: updates.enabled ?? registry.enabled
- });
-
- registries = await templateService.getRegistries();
- templates = await templateService.getTemplates(requestOptions);
- toast.success(m.common_update_success({ resource: m.resource_registry() }));
- } catch (error) {
- console.error('Error updating registry:', error);
- toast.error(error instanceof Error ? error.message : m.registries_save_failed());
} finally {
delete isLoading.updating[id];
}
@@ -81,29 +89,41 @@
isLoading.removing[id] = true;
try {
- const reg = registries.find((r) => r.id === id);
- await templateService.deleteRegistry(id);
- registries = registries.filter((r) => r.id !== id);
- registries = await templateService.getRegistries();
- templates = await templateService.getTemplates(requestOptions);
- toast.success(
- reg
- ? m.common_delete_success({ resource: `${m.resource_registry()} "${reg.url}"` })
- : m.templates_registry_removed_success()
+ const operationResult = await tryCatch(
+ (async () => {
+ const reg = registries.find((r) => r.id === id);
+ await templateService.deleteRegistry(id);
+ registries = registries.filter((r) => r.id !== id);
+ registries = await templateService.getRegistries();
+ templates = await templateService.getTemplates(requestOptions);
+ toast.success(
+ reg
+ ? m.common_delete_success({ resource: `${m.resource_registry()} "${reg.url}"` })
+ : m.templates_registry_removed_success()
+ );
+ })()
);
- } catch (error) {
- console.error('Error removing registry:', error);
- toast.error(error instanceof Error ? error.message : m.registries_save_failed());
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error removing registry:', error);
+ toast.error(error instanceof Error ? error.message : m.registries_save_failed());
+ }
} finally {
delete isLoading.removing[id];
}
}
async function refreshTemplates() {
- try {
- templates = await templateService.getTemplates(requestOptions);
- toast.success(m.templates_refreshed());
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ templates = await templateService.getTemplates(requestOptions);
+ toast.success(m.templates_refreshed());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Error refreshing templates:', error);
toast.error(m.common_refresh_failed({ resource: m.templates_title() }));
}
@@ -113,21 +133,28 @@
isLoading.addingRegistry = true;
try {
- await templateService.addRegistry({
- name: registry.name.trim(),
- url: registry.url.trim(),
- description: registry.description?.trim() || undefined,
- enabled: registry.enabled
- });
-
- registries = await templateService.getRegistries();
- templates = await templateService.getTemplates(requestOptions);
- showAddRegistrySheet = false;
+ const operationResult = await tryCatch(
+ (async () => {
+ await templateService.addRegistry({
+ name: registry.name.trim(),
+ url: registry.url.trim(),
+ description: registry.description?.trim() || undefined,
+ enabled: registry.enabled
+ });
+
+ registries = await templateService.getRegistries();
+ templates = await templateService.getTemplates(requestOptions);
+ showAddRegistrySheet = false;
+
+ toast.success(m.common_create_success({ resource: m.resource_registry() }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- toast.success(m.common_create_success({ resource: m.resource_registry() }));
- } catch (error) {
- console.error('Error adding registry:', error);
- toast.error(error instanceof Error ? error.message : m.registries_save_failed());
+ console.error('Error adding registry:', error);
+ toast.error(error instanceof Error ? error.message : m.registries_save_failed());
+ }
} finally {
isLoading.addingRegistry = false;
}
diff --git a/frontend/src/routes/(app)/customize/templates/+page.ts b/frontend/src/routes/(app)/customize/templates/+page.ts
index 049334184..822028b38 100644
--- a/frontend/src/routes/(app)/customize/templates/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { templateService } from '#lib/services/template-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { Template, TemplateRegistry } from '#lib/types/swarm.js';
@@ -20,21 +21,25 @@ export const load: PageLoad = async ({
} satisfies SearchPaginationSortRequest);
const [templates, registries] = await Promise.all([
- queryClient
- .fetchQuery({
+ tryCatch(
+ queryClient.fetchQuery({
queryKey: queryKeys.templates.list(templateRequestOptions),
queryFn: () => templateService.getTemplates(templateRequestOptions)
})
- .catch(() => ({
- data: [],
- pagination: { currentPage: 1, totalPages: 0, totalItems: 0, itemsPerPage: 20 }
- })),
- queryClient
- .fetchQuery({
+ ).then((result) =>
+ result.error
+ ? {
+ data: [],
+ pagination: { currentPage: 1, totalPages: 0, totalItems: 0, itemsPerPage: 20 }
+ }
+ : result.data
+ ),
+ tryCatch(
+ queryClient.fetchQuery({
queryKey: queryKeys.templates.registries(),
queryFn: () => templateService.getRegistries()
})
- .catch(() => [])
+ ).then((result) => (result.error ? [] : result.data))
]);
return {
diff --git a/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte b/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte
index 7598904e9..5385c5a1f 100644
--- a/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { Badge } from '#lib/components/ui/badge/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
@@ -139,16 +141,23 @@
if (status.isDownloading || !canDownload) return;
status.isDownloading = true;
try {
- const downloadedTemplate = await templateService.download(template.id);
- toast.success(m.templates_downloaded_success({ name: template.name }));
- if (downloadedTemplate?.id) {
- await goto(`/customize/templates/${downloadedTemplate.id}`, { replaceState: true });
- } else {
- await refreshAll();
+ const operationResult = await tryCatch(
+ (async () => {
+ const downloadedTemplate = await templateService.download(template.id);
+ toast.success(m.templates_downloaded_success({ name: template.name }));
+ if (downloadedTemplate?.id) {
+ await goto(`/customize/templates/${downloadedTemplate.id}`, { replaceState: true });
+ } else {
+ await refreshAll();
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error downloading template:', error);
+ toast.error(error instanceof Error ? error.message : m.templates_download_failed());
}
- } catch (error) {
- console.error('Error downloading template:', error);
- toast.error(error instanceof Error ? error.message : m.templates_download_failed());
} finally {
status.isDownloading = false;
}
@@ -164,11 +173,16 @@
destructive: true,
action: async () => {
status.isDeleting = true;
- try {
- await templateService.deleteTemplate(template.id);
- toast.success(m.common_delete_success({ resource: `${m.resource_template()} "${template.name}"` }));
- await goto('/customize/templates');
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await templateService.deleteTemplate(template.id);
+ toast.success(m.common_delete_success({ resource: `${m.resource_template()} "${template.name}"` }));
+ await goto('/customize/templates');
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Error deleting template:', error);
toast.error(
error instanceof Error
diff --git a/frontend/src/routes/(app)/customize/templates/[id]/+page.ts b/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
index 9aba93871..cf8c163d3 100644
--- a/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { templateService } from '#lib/services/template-service.js';
import { variableService } from '#lib/services/variable-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -16,31 +17,38 @@ export const load: PageLoad = async ({
}> => {
const { queryClient } = await parent();
- try {
- const [templateData, allTemplates, globalVariables] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.templates.content(params.id),
- queryFn: () => templateService.getTemplateContent(params.id)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.templates.allTemplates(),
- queryFn: () => templateService.getAllTemplates()
- }),
- queryClient
- .fetchQuery({
- queryKey: queryKeys.variables.list(),
- queryFn: () => variableService.list()
- })
- .catch(() => [] as GlobalVariable[])
- ]);
+ const operationResult = await tryCatch(
+ (async () => {
+ const [templateData, allTemplates, globalVariables] = await Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.templates.content(params.id),
+ queryFn: () => templateService.getTemplateContent(params.id)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.templates.allTemplates(),
+ queryFn: () => templateService.getAllTemplates()
+ }),
+ tryCatch(
+ queryClient.fetchQuery({
+ queryKey: queryKeys.variables.list(),
+ queryFn: () => variableService.list()
+ })
+ ).then((result) => (result.error ? ([] as GlobalVariable[]) : result.data))
+ ]);
+
+ return {
+ templateData,
+ allTemplates,
+ globalVariables
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- return {
- templateData,
- allTemplates,
- globalVariables
- };
- } catch (err) {
console.error('Failed to load template:', err);
throw error(404, 'Template not found');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/customize/templates/components/template-gallery.svelte b/frontend/src/routes/(app)/customize/templates/components/template-gallery.svelte
index 12334e69d..9944acd41 100644
--- a/frontend/src/routes/(app)/customize/templates/components/template-gallery.svelte
+++ b/frontend/src/routes/(app)/customize/templates/components/template-gallery.svelte
@@ -6,7 +6,8 @@
import TemplateCard from './template-card.svelte';
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { templateService } from '#lib/services/template-service.js';
import { templateTypeFilters } from '#lib/components/arcane-table/data.js';
import { debounced } from '#lib/utils/ws.js';
@@ -109,7 +110,7 @@
deletingId = template.id;
const result = await tryCatch(templateService.deleteTemplate(template.id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_delete_failed({ resource: `${m.resource_template()} "${template.name}"` }),
setLoadingState: (value) => (value ? null : (deletingId = null)),
@@ -128,7 +129,7 @@
downloadingId = template.id;
const result = await tryCatch(templateService.download(template.id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.templates_download_failed(),
setLoadingState: (value) => (value ? null : (downloadingId = null)),
diff --git a/frontend/src/routes/(app)/customize/templates/create/+page.svelte b/frontend/src/routes/(app)/customize/templates/create/+page.svelte
index dca0109bf..f712795a5 100644
--- a/frontend/src/routes/(app)/customize/templates/create/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/create/+page.svelte
@@ -5,7 +5,7 @@
import { templateService } from '#lib/services/template-service.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { createForm } from '#lib/utils/settings.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import TemplateEditorWorkspace from '../components/template-editor-workspace.svelte';
import { globalVariablesToMap } from '#lib/utils/template-load.js';
@@ -63,7 +63,8 @@
);
if (!validated) return;
- handleApiResultWithCallbacks({
+ saving = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(
templateService.createTemplate({
name: validated.name,
diff --git a/frontend/src/routes/(app)/customize/templates/create/+page.ts b/frontend/src/routes/(app)/customize/templates/create/+page.ts
index 917df471f..46814b99a 100644
--- a/frontend/src/routes/(app)/customize/templates/create/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/create/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { variableService } from '#lib/services/variable-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { GlobalVariable } from '#lib/types/variable.js';
@@ -6,12 +7,12 @@ import type { PageLoad } from './$types';
export const load: PageLoad = async ({ parent }): Promise<{ globalVariables: GlobalVariable[] }> => {
const { queryClient } = await parent();
- const globalVariables = await queryClient
- .fetchQuery({
+ const globalVariables = await tryCatch(
+ queryClient.fetchQuery({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
- .catch(() => [] as GlobalVariable[]);
+ ).then((result) => (result.error ? ([] as GlobalVariable[]) : result.data));
return { globalVariables };
};
diff --git a/frontend/src/routes/(app)/customize/templates/default/+page.svelte b/frontend/src/routes/(app)/customize/templates/default/+page.svelte
index a66ac35e3..df3ebe7fb 100644
--- a/frontend/src/routes/(app)/customize/templates/default/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/default/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { toast } from 'svelte-sonner';
import { createForm } from '#lib/utils/settings.js';
@@ -86,13 +88,20 @@
ui.isLoadingTemplate = true;
try {
- const templateContent = await templateService.getTemplateContent(template.id);
- $inputs.composeContent.value = templateContent.content ?? template.content ?? '';
- $inputs.envContent.value = templateContent.envContent ?? template.envContent ?? '';
- toast.success(m.compose_template_loaded({ name: template.name }));
- } catch (error) {
- console.error('Error loading template:', error);
- toast.error(error instanceof Error ? error.message : m.templates_download_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const templateContent = await templateService.getTemplateContent(template.id);
+ $inputs.composeContent.value = templateContent.content ?? template.content ?? '';
+ $inputs.envContent.value = templateContent.envContent ?? template.envContent ?? '';
+ toast.success(m.compose_template_loaded({ name: template.name }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error loading template:', error);
+ toast.error(error instanceof Error ? error.message : m.templates_download_failed());
+ }
} finally {
ui.isLoadingTemplate = false;
}
diff --git a/frontend/src/routes/(app)/customize/variables/+page.svelte b/frontend/src/routes/(app)/customize/variables/+page.svelte
index 06f2bbae1..b9ea94f7a 100644
--- a/frontend/src/routes/(app)/customize/variables/+page.svelte
+++ b/frontend/src/routes/(app)/customize/variables/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { toast } from 'svelte-sonner';
import { ResourcePageLayout, type ActionButton } from '#lib/layouts/index.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
@@ -52,39 +54,46 @@
async function handleSheetSubmit(payload: VariableFormPayload) {
isSubmitting = true;
try {
- let response;
- if (payload.mode === 'edit') {
- response = await variableService.update(payload.id, payload.variable);
- } else if (payload.mode === 'bulk') {
- response = await variableService.createMany(payload.variables);
- } else {
- response = await variableService.create(payload.variable);
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ let response;
+ if (payload.mode === 'edit') {
+ response = await variableService.update(payload.id, payload.variable);
+ } else if (payload.mode === 'bulk') {
+ response = await variableService.createMany(payload.variables);
+ } else {
+ response = await variableService.create(payload.variable);
+ }
- variables = await variableService.list();
+ variables = await variableService.list();
- if (payload.mode === 'bulk') {
- toast.success(m.count_variables_created({ count: payload.variables.length }));
- } else if (payload.mode === 'edit') {
- toast.success(m.common_update_success({ resource: m.variable() }));
- } else {
- toast.success(m.common_create_success({ resource: m.variable() }));
- }
- reportSyncResults(response?.syncResults);
-
- isSheetOpen = false;
- variableToEdit = null;
- } catch (error) {
- console.error('Error saving variable:', error);
- toast.error(
- payload.mode === 'edit'
- ? m.common_update_failed({ resource: m.variable() })
- : m.common_create_failed({ resource: m.variable() })
+ if (payload.mode === 'bulk') {
+ toast.success(m.count_variables_created({ count: payload.variables.length }));
+ } else if (payload.mode === 'edit') {
+ toast.success(m.common_update_success({ resource: m.variable() }));
+ } else {
+ toast.success(m.common_create_success({ resource: m.variable() }));
+ }
+ reportSyncResults(response?.syncResults);
+
+ isSheetOpen = false;
+ variableToEdit = null;
+ })()
);
- // A bulk create can partially succeed before the failing entry, so
- // refresh even on error to keep the table and duplicate-key
- // validation in sync with what was actually persisted.
- variables = await variableService.list().catch(() => variables);
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error saving variable:', error);
+ toast.error(
+ payload.mode === 'edit'
+ ? m.common_update_failed({ resource: m.variable() })
+ : m.common_create_failed({ resource: m.variable() })
+ );
+ // A bulk create can partially succeed before the failing entry, so
+ // refresh even on error to keep the table and duplicate-key
+ // validation in sync with what was actually persisted.
+ variables = await tryCatch(variableService.list()).then((result) => (result.error ? variables : result.data));
+ }
} finally {
isSubmitting = false;
}
@@ -98,15 +107,20 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- try {
- const response = await variableService.delete(variable.id);
- variables = await variableService.list();
- toast.success(m.common_delete_success({ resource: m.variable() }));
- reportSyncResults(response?.syncResults);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await variableService.delete(variable.id);
+ variables = await variableService.list();
+ toast.success(m.common_delete_success({ resource: m.variable() }));
+ reportSyncResults(response?.syncResults);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Error deleting variable:', error);
toast.error(m.common_delete_failed({ resource: m.variable() }));
- variables = await variableService.list().catch(() => variables);
+ variables = await tryCatch(variableService.list()).then((result) => (result.error ? variables : result.data));
}
}
}
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
index 6ae848a96..77f24c0b4 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
@@ -27,7 +27,7 @@
import type { PruneType, SystemPruneRequest } from '#lib/types/automation.js';
import type { AppVersionInformation, Settings } from '#lib/types/settings.js';
import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { isEnvironmentOnline } from '#lib/utils/docker.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { createStatsWebSocket, type ReconnectingWebSocket } from '#lib/utils/ws.js';
@@ -215,9 +215,14 @@
return;
}
- dockerInfoPromise = loadDockerInfo(environment).catch((error) => {
- dockerInfoError = extractApiErrorMessage(error);
- throw error;
+ dockerInfoPromise = tryCatch(loadDockerInfo(environment)).then((result) => {
+ if (result.error) {
+ const error: Error = result.error;
+
+ dockerInfoError = extractApiErrorMessage(error);
+ throw error;
+ }
+ return result.data;
});
dockerInfoPromiseByEnvironmentId[environment.id] = dockerInfoPromise;
}
@@ -378,10 +383,15 @@
return;
}
- try {
- await environmentStore.setEnvironment(environment);
- toast.success(m.environments_switched_to({ name: environment.name }));
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await environmentStore.setEnvironment(environment);
+ toast.success(m.environments_switched_to({ name: environment.name }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to switch environment:', error);
toast.error(m.common_update_failed({ resource: m.resource_environment() }));
}
@@ -518,11 +528,13 @@
pruneEnvironment = item;
pruneDefaultsLoadingId = environmentId;
try {
- // Pre-fill the dialog with this environment's configured prune defaults.
- pruneDefaults = await settingsService.getSettingsForEnvironment(environmentId);
- } catch {
- // Fall back to the dialog's built-in defaults if settings can't be loaded.
- pruneDefaults = null;
+ const operationResult = await tryCatch((async () => settingsService.getSettingsForEnvironment(environmentId))());
+ if (operationResult.error !== null) {
+ // Fall back to the dialog's built-in defaults if settings can't be loaded.
+ pruneDefaults = null;
+ } else {
+ pruneDefaults = operationResult.data;
+ }
} finally {
pruneDefaultsLoadingId = null;
}
@@ -563,7 +575,7 @@
pruningEnvironmentId = environmentId;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(systemService.pruneAllForEnvironment(environmentId, pruneRequest)),
message: m.dashboard_prune_failed({ types: typesString }),
setLoadingState: (value) => {
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
index 51cbfc50f..60db19b72 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { toast } from 'svelte-sonner';
import { createQuery } from '@tanstack/svelte-query';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -95,17 +97,24 @@
});
async function handleConfirmUpgradeInternal() {
- try {
- const result = await systemUpgradeService.triggerUpgrade(environment.id);
- if (!result.success) {
- throw new Error(result.error || result.message || m.common_unknown());
- }
- toast.success(m.upgrade_success());
- await onRefreshRequested?.();
- return { upToDate: result.upToDate };
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await systemUpgradeService.triggerUpgrade(environment.id);
+ if (!result.success) {
+ throw new Error(result.error || result.message || m.common_unknown());
+ }
+ toast.success(m.upgrade_success());
+ await onRefreshRequested?.();
+ return { upToDate: result.upToDate };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toastUpgradeError(error, m.upgrade_failed);
throw error;
+ } else {
+ return operationResult.data;
}
}
</script>
diff --git a/frontend/src/routes/(app)/environments/+page.ts b/frontend/src/routes/(app)/environments/+page.ts
index 9b91e9dc0..c9b4763b6 100644
--- a/frontend/src/routes/(app)/environments/+page.ts
+++ b/frontend/src/routes/(app)/environments/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
@@ -20,13 +21,19 @@ export const load: PageLoad = async ({ parent }) => {
} satisfies SearchPaginationSortRequest);
let environments;
- try {
- environments = await queryClient.fetchQuery({
- queryKey: queryKeys.environments.list(environmentRequestOptions),
- queryFn: () => environmentManagementService.getEnvironments(environmentRequestOptions)
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.environments.list(environmentRequestOptions),
+ queryFn: () => environmentManagementService.getEnvironments(environmentRequestOptions)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load environments');
+ } else {
+ environments = operationResult.data;
}
return { environments, environmentRequestOptions };
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index 771f397bb..68321d283 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { onMount } from 'svelte';
import * as Tabs from '#lib/components/ui/tabs/index.js';
import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';
@@ -440,22 +442,34 @@
});
async function refreshRuntimeEnvironment() {
- try {
- const latestEnvironment = await environmentManagementService.get(environment.id);
- if (latestEnvironment.id === environment.id) {
- refreshedEnvironment = latestEnvironment;
- }
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const latestEnvironment = await environmentManagementService.get(environment.id);
+ if (latestEnvironment.id === environment.id) {
+ refreshedEnvironment = latestEnvironment;
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.debug('Failed to refresh environment runtime state:', error);
}
}
async function fetchVersion() {
try {
- isLoadingVersion = true;
- remoteVersion = await environmentManagementService.getVersion(environment.id);
- } catch (err) {
- console.error('Failed to fetch environment version:', err);
+ const operationResult = await tryCatch(
+ (async () => {
+ isLoadingVersion = true;
+ remoteVersion = await environmentManagementService.getVersion(environment.id);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ console.error('Failed to fetch environment version:', err);
+ }
} finally {
isLoadingVersion = false;
}
@@ -464,13 +478,20 @@
async function refreshEnvironment() {
if (isRefreshing) return;
try {
- isRefreshing = true;
- statusOverride = null;
- remoteVersion = null;
- await refreshAll();
- } catch (err) {
- console.error('Failed to refresh environment:', err);
- toast.error(m.common_refresh_failed({ resource: m.resource_environment() }));
+ const operationResult = await tryCatch(
+ (async () => {
+ isRefreshing = true;
+ statusOverride = null;
+ remoteVersion = null;
+ await refreshAll();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ console.error('Failed to refresh environment:', err);
+ toast.error(m.common_refresh_failed({ resource: m.resource_environment() }));
+ }
} finally {
isRefreshing = false;
}
@@ -479,12 +500,19 @@
async function syncEnvironment() {
if (isSyncing) return;
try {
- isSyncing = true;
- await environmentManagementService.sync(environment.id);
- toast.success(m.sync_environment_success());
- } catch (error) {
- console.error('Failed to sync environment:', error);
- toast.error(m.sync_environment_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ isSyncing = true;
+ await environmentManagementService.sync(environment.id);
+ toast.success(m.sync_environment_success());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Failed to sync environment:', error);
+ toast.error(m.sync_environment_failed());
+ }
} finally {
isSyncing = false;
}
@@ -493,27 +521,34 @@
async function testConnection() {
if (isTestingConnection) return;
try {
- isTestingConnection = true;
- const customUrl = $formInputs.apiUrl.value !== environment.apiUrl ? $formInputs.apiUrl.value : undefined;
- const result = await environmentManagementService.testConnection(environment.id, customUrl);
-
- const nextStatus = result.status as EnvironmentStatus;
- statusOverride = customUrl && !environment.isEdge ? nextStatus : null;
-
- if (result.status === 'online') {
- toast.success(m.environments_test_connection_success());
- } else {
- toast.error(m.environments_test_connection_error());
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ isTestingConnection = true;
+ const customUrl = $formInputs.apiUrl.value !== environment.apiUrl ? $formInputs.apiUrl.value : undefined;
+ const result = await environmentManagementService.testConnection(environment.id, customUrl);
+
+ const nextStatus = result.status as EnvironmentStatus;
+ statusOverride = customUrl && !environment.isEdge ? nextStatus : null;
+
+ if (result.status === 'online') {
+ toast.success(m.environments_test_connection_success());
+ } else {
+ toast.error(m.environments_test_connection_error());
+ }
+
+ // If testing with saved URL (not custom), refresh to get backend's updated status
+ if (!customUrl) {
+ await refreshAll();
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- // If testing with saved URL (not custom), refresh to get backend's updated status
- if (!customUrl) {
- await refreshAll();
+ statusOverride = environment.isEdge ? null : 'offline';
+ toast.error(m.environments_test_connection_failed());
+ console.error(error);
}
- } catch (error) {
- statusOverride = environment.isEdge ? null : 'offline';
- toast.error(m.environments_test_connection_failed());
- console.error(error);
} finally {
isTestingConnection = false;
}
@@ -521,23 +556,30 @@
async function handleRegenerateApiKey() {
try {
- isRegeneratingKey = true;
-
- // Delete the old API key and create a new one
- const result = await environmentManagementService.update(environment.id, {
- regenerateApiKey: true
- });
+ const operationResult = await tryCatch(
+ (async () => {
+ isRegeneratingKey = true;
+
+ // Delete the old API key and create a new one
+ const result = await environmentManagementService.update(environment.id, {
+ regenerateApiKey: true
+ });
+
+ if (result.apiKey) {
+ regeneratedApiKey = result.apiKey;
+ toast.success(m.environments_regenerate_key_success());
+ await refreshAll();
+ } else {
+ toast.error(m.environments_regenerate_key_failed());
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- if (result.apiKey) {
- regeneratedApiKey = result.apiKey;
- toast.success(m.environments_regenerate_key_success());
- await refreshAll();
- } else {
+ console.error('Failed to regenerate API key:', error);
toast.error(m.environments_regenerate_key_failed());
}
- } catch (error) {
- console.error('Failed to regenerate API key:', error);
- toast.error(m.environments_regenerate_key_failed());
} finally {
isRegeneratingKey = false;
showRegenerateDialog = false;
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.ts b/frontend/src/routes/(app)/environments/[id]/+page.ts
index d21b7d18b..cf36e1c41 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.ts
+++ b/frontend/src/routes/(app)/environments/[id]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
import { settingsService } from '#lib/services/settings-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -6,26 +7,38 @@ import type { PageLoad } from './$types';
export const load: PageLoad = async ({ params, parent }) => {
const { queryClient } = await parent();
- try {
- const environment = await queryClient.fetchQuery({
- queryKey: queryKeys.environments.detail(params.id),
- queryFn: () => environmentManagementService.get(params.id)
- });
-
- let settings = null;
- try {
- settings = await queryClient.fetchQuery({
- queryKey: queryKeys.environments.settings(params.id),
- queryFn: () => settingsService.getSettingsForEnvironment(params.id)
+ const operationResult = await tryCatch(
+ (async () => {
+ const environment = await queryClient.fetchQuery({
+ queryKey: queryKeys.environments.detail(params.id),
+ queryFn: () => environmentManagementService.get(params.id)
});
- } catch {}
- return {
- environment,
- settings
- };
- } catch (error) {
+ let settings = null;
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.environments.settings(params.id),
+ queryFn: () => settingsService.getSettingsForEnvironment(params.id)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ } else {
+ settings = operationResult.data;
+ }
+
+ return {
+ environment,
+ settings
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to load environment:', error);
throw error;
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
index 867fcde66..75c6e08f5 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
@@ -4,7 +4,7 @@
import { SvelteSet } from 'svelte/reactivity';
import { jobScheduleService } from '#lib/services/job-schedule-service.js';
import { containerService } from '#lib/services/container-service.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import JobCard from '#lib/components/job-card/job-card.svelte';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { m } from '#lib/paraglide/messages.js';
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
index 20dbbb6b0..1a19b7abe 100644
--- a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
@@ -9,7 +9,8 @@
} from '#lib/types/automation.js';
import GitOpsSyncFormSheet from '#lib/components/dialogs/gitops-sync-dialog.svelte';
import GitOpsImportDialog from '#lib/components/dialogs/gitops-import-dialog.svelte';
- import { extractApiErrorMessage, handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { m } from '#lib/paraglide/messages.js';
import { gitOpsSyncService } from '#lib/services/gitops-sync-service.js';
import { page } from '$app/state';
@@ -65,7 +66,7 @@
async function refreshSyncs() {
isLoading.refresh = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(gitOpsSyncService.getSyncs(environmentId, syncRequestOptions)),
message: m.common_refresh_failed({ resource: m.git_syncs_title() }),
setLoadingState: (value) => (isLoading.refresh = value),
@@ -94,22 +95,29 @@
isLoading[loadingKey] = true;
try {
- if (isEditMode && syncToEdit?.id) {
- await gitOpsSyncService.updateSync(environmentId, syncToEdit.id, sync as GitOpsSyncUpdateDto);
- toast.success(m.common_update_success({ resource: m.resource_sync() }));
- } else {
- await gitOpsSyncService.createSync(environmentId, sync as GitOpsSyncCreateDto);
- toast.success(m.common_create_success({ resource: m.resource_sync() }));
+ const operationResult = await tryCatch(
+ (async () => {
+ if (isEditMode && syncToEdit?.id) {
+ await gitOpsSyncService.updateSync(environmentId, syncToEdit.id, sync as GitOpsSyncUpdateDto);
+ toast.success(m.common_update_success({ resource: m.resource_sync() }));
+ } else {
+ await gitOpsSyncService.createSync(environmentId, sync as GitOpsSyncCreateDto);
+ toast.success(m.common_create_success({ resource: m.resource_sync() }));
+ }
+
+ syncs = await gitOpsSyncService.getSyncs(environmentId, syncRequestOptions);
+ isSyncDialogOpen = false;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error saving sync:', error);
+ const title = isEditMode
+ ? m.common_update_failed({ resource: m.resource_sync() })
+ : m.common_create_failed({ resource: m.resource_sync() });
+ toast.error(title, { description: extractApiErrorMessage(error) });
}
-
- syncs = await gitOpsSyncService.getSyncs(environmentId, syncRequestOptions);
- isSyncDialogOpen = false;
- } catch (error) {
- console.error('Error saving sync:', error);
- const title = isEditMode
- ? m.common_update_failed({ resource: m.resource_sync() })
- : m.common_create_failed({ resource: m.resource_sync() });
- toast.error(title, { description: extractApiErrorMessage(error) });
} finally {
isLoading[loadingKey] = false;
}
@@ -118,32 +126,39 @@
async function handleImportSubmit(data: ImportGitOpsSyncRequest[]) {
isLoading.import = true;
try {
- const response = await gitOpsSyncService.importSyncs(environmentId, data);
-
- if (response.failedCount === 0) {
- toast.success(m.git_sync_import_success({ count: response.successCount }));
- isImportDialogOpen = false;
- } else {
- if (response.successCount > 0) {
- toast.warning(
- m.git_sync_import_partial_success({ successCount: response.successCount, failedCount: response.failedCount })
- );
- } else {
- toast.error(m.git_sync_import_failed_count({ count: response.failedCount }));
- }
-
- // Show error details
- if (response.errors && response.errors.length > 0) {
- console.error('Import errors:', response.errors);
- // Could show a dialog with errors here, for now just toast the first few
- response.errors.slice(0, 3).forEach((err) => toast.error(err));
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await gitOpsSyncService.importSyncs(environmentId, data);
+
+ if (response.failedCount === 0) {
+ toast.success(m.git_sync_import_success({ count: response.successCount }));
+ isImportDialogOpen = false;
+ } else {
+ if (response.successCount > 0) {
+ toast.warning(
+ m.git_sync_import_partial_success({ successCount: response.successCount, failedCount: response.failedCount })
+ );
+ } else {
+ toast.error(m.git_sync_import_failed_count({ count: response.failedCount }));
+ }
+
+ // Show error details
+ if (response.errors && response.errors.length > 0) {
+ console.error('Import errors:', response.errors);
+ // Could show a dialog with errors here, for now just toast the first few
+ response.errors.slice(0, 3).forEach((err) => toast.error(err));
+ }
+ }
+
+ syncs = await gitOpsSyncService.getSyncs(environmentId, syncRequestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error importing syncs:', error);
+ toast.error(error instanceof Error ? error.message : m.git_sync_import_failed());
}
-
- syncs = await gitOpsSyncService.getSyncs(environmentId, syncRequestOptions);
- } catch (error) {
- console.error('Error importing syncs:', error);
- toast.error(error instanceof Error ? error.message : m.git_sync_import_failed());
} finally {
isLoading.import = false;
}
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
index 4b3b5c47e..11498bf12 100644
--- a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
@@ -7,7 +7,7 @@
import RemoveMenuItem from '#lib/components/arcane-table/cells/remove-menu-item.svelte';
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { GitOpsSync } from '#lib/types/automation.js';
import type { ColumnSpec, BulkAction, ArcaneRow } from '#lib/components/arcane-table/index.js';
@@ -106,7 +106,7 @@
async function handlePerformSync(id: string, _name: string) {
isLoading.syncing = true;
const result = await tryCatch(gitOpsSyncService.performSync(environmentId, id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.git_sync_failed(),
setLoadingState: () => {},
diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelte
index 17ca313eb..95b1db147 100644
--- a/frontend/src/routes/(app)/environments/environment-table.svelte
+++ b/frontend/src/routes/(app)/environments/environment-table.svelte
@@ -6,7 +6,7 @@
import { goto } from '$app/navigation';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import { toastUpgradeError } from '#lib/utils/api.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -103,7 +103,7 @@
action: async () => {
isLoading.removing = true;
const result = await tryCatch(environmentManagementService.delete(id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.environments_delete_failed({ name: hostname }),
setLoadingState: () => {},
@@ -122,7 +122,7 @@
async function handleTest(id: string) {
isLoading.testing = true;
const result = await tryCatch(environmentManagementService.testConnection(id));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.environments_test_connection_failed(),
setLoadingState: () => {},
@@ -150,16 +150,23 @@
const envId = selectedEnvironmentForUpgrade.id;
upgradingEnvironmentId = envId;
- try {
- const result = await systemUpgradeService.triggerUpgrade(envId);
- if (!result.success) {
- throw new Error(result.error || m.upgrade_failed({ error: m.common_unknown() }));
- }
- toast.success(m.upgrade_success());
- return { upToDate: result.upToDate };
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await systemUpgradeService.triggerUpgrade(envId);
+ if (!result.success) {
+ throw new Error(result.error || m.upgrade_failed({ error: m.common_unknown() }));
+ }
+ toast.success(m.upgrade_success());
+ return { upToDate: result.upToDate };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toastUpgradeError(error, m.upgrade_failed);
throw error;
+ } else {
+ return operationResult.data;
}
}
@@ -177,7 +184,7 @@
const result = await tryCatch(environmentManagementService.update(environment.id, { enabled: newEnabled }));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_update_failed({ resource: m.resource_environment() }),
setLoadingState: () => {},
@@ -362,12 +369,13 @@
toast.error(m.environments_cannot_switch_disabled());
return;
}
- try {
- await environmentStore.setEnvironment(item);
- toast.success(m.environments_switched_to({ name: item.name }));
- } catch (error) {
- console.error('Failed to set environment:', error);
- }
+ const result = await tryCatch(
+ (async () => {
+ await environmentStore.setEnvironment(item);
+ toast.success(m.environments_switched_to({ name: item.name }));
+ })()
+ );
+ if (result.error) console.error('Failed to set environment:', result.error);
}}
disabled={!item.enabled || environmentStore.selected?.id === item.id}
>
diff --git a/frontend/src/routes/(app)/events/+page.ts b/frontend/src/routes/(app)/events/+page.ts
index 8039dbe33..bb301f972 100644
--- a/frontend/src/routes/(app)/events/+page.ts
+++ b/frontend/src/routes/(app)/events/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { eventService } from '#lib/services/event-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -21,19 +22,25 @@ export const load: PageLoad = async ({ parent }) => {
let events;
let eventStats;
- try {
- [events, eventStats] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.events.listGlobal(eventRequestOptions),
- queryFn: () => eventService.getEvents(eventRequestOptions)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.events.statsGlobal(),
- queryFn: () => eventService.getEventStats()
- })
- ]);
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.events.listGlobal(eventRequestOptions),
+ queryFn: () => eventService.getEvents(eventRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.events.statsGlobal(),
+ queryFn: () => eventService.getEventStats()
+ })
+ ]))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load events');
+ } else {
+ [events, eventStats] = operationResult.data;
}
return { events, eventStats, eventRequestOptions };
diff --git a/frontend/src/routes/(app)/events/event-table.svelte b/frontend/src/routes/(app)/events/event-table.svelte
index ecb7e3b61..00797242e 100644
--- a/frontend/src/routes/(app)/events/event-table.svelte
+++ b/frontend/src/routes/(app)/events/event-table.svelte
@@ -5,7 +5,7 @@
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { formatRelativeTime } from '#lib/utils/formatting.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -60,7 +60,7 @@
destructive: true,
action: async () => {
isLoading.removing = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(eventService.delete(eventId)),
message: m.events_delete_failed({ title: safeTitle }),
setLoadingState: (value) => (isLoading.removing = value),
diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelte
index 62019cae4..7d2468a30 100644
--- a/frontend/src/routes/(app)/images/+page.svelte
+++ b/frontend/src/routes/(app)/images/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { toast } from 'svelte-sonner';
@@ -116,10 +118,15 @@
mutationFn: async ({ files, requestedEnvId }: { files: File[]; requestedEnvId: string }) => {
for (const file of files) {
try {
- await imageService.uploadImage(file, requestedEnvId, (progress) => (uploadProgress = progress));
- toast.success(m.images_upload_success());
- } catch {
- toast.error(m.images_upload_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ await imageService.uploadImage(file, requestedEnvId, (progress) => (uploadProgress = progress));
+ toast.success(m.images_upload_success());
+ })()
+ );
+ if (operationResult.error !== null) {
+ toast.error(m.images_upload_failed());
+ }
} finally {
uploadProgress = null;
}
diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.ts
index 14f8259ce..61a466854 100644
--- a/frontend/src/routes/(app)/images/+page.ts
+++ b/frontend/src/routes/(app)/images/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { imageService } from '#lib/services/image-service.js';
import { settingsService } from '#lib/services/settings-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -17,23 +18,29 @@ export const load: PageLoad = async ({ parent }) => {
let images;
let settings;
let imageUsageCounts;
- try {
- [images, settings, imageUsageCounts] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.images.list(envId, imageRequestOptions),
- queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.images.usageCounts(envId),
- queryFn: () => imageService.getImageUsageCountsForEnvironment(envId)
- })
- ]);
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.images.list(envId, imageRequestOptions),
+ queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.settings.byEnvironment(envId),
+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.images.usageCounts(envId),
+ queryFn: () => imageService.getImageUsageCountsForEnvironment(envId)
+ })
+ ]))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load images');
+ } else {
+ [images, settings, imageUsageCounts] = operationResult.data;
}
return { envId, images, imageRequestOptions, settings, imageUsageCounts };
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index c4de53009..bc602d478 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -5,7 +5,7 @@
import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import { onDestroy } from 'svelte';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -89,11 +89,14 @@
async function loadVulnerabilityScan() {
if (!image?.id) return;
- try {
- const result = await vulnerabilityService.getScanResult(image.id);
- vulnerabilityScan = result;
- lastScanRequestedAt = result.scanTime || lastScanRequestedAt;
- } catch {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await vulnerabilityService.getScanResult(image.id);
+ vulnerabilityScan = result;
+ lastScanRequestedAt = result.scanTime || lastScanRequestedAt;
+ })()
+ );
+ if (operationResult.error !== null) {
// No scan data found, that's okay
vulnerabilityScan = null;
}
@@ -104,18 +107,25 @@
if (!image?.id || isLoading.scanning) return;
isLoading.scanning = true;
try {
- const result = await vulnerabilityService.scanImage(image.id);
- vulnerabilityScan = result;
- lastScanRequestedAt = result.scanTime || nowInstantString();
- if (isVulnerabilityScanInProgress(result.status)) {
- toastVulnerabilityScanStatus(result, { includeStarted: true });
- beginScanPolling(true);
- } else {
- toastVulnerabilityScanStatus(result);
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await vulnerabilityService.scanImage(image.id);
+ vulnerabilityScan = result;
+ lastScanRequestedAt = result.scanTime || nowInstantString();
+ if (isVulnerabilityScanInProgress(result.status)) {
+ toastVulnerabilityScanStatus(result, { includeStarted: true });
+ beginScanPolling(true);
+ } else {
+ toastVulnerabilityScanStatus(result);
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Failed to scan image:', error);
+ toast.error(m.vuln_scan_failed());
}
- } catch (error) {
- console.error('Failed to scan image:', error);
- toast.error(m.vuln_scan_failed());
} finally {
isLoading.scanning = false;
}
@@ -129,7 +139,7 @@
// patching all outdated OS packages.
const options = vulnerabilityScan?.hasReport ? { scanId: image.id } : undefined;
const result = await tryCatch(imageService.patchImage(image.id, options));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.images_patch_failed(),
setLoadingState: (value) => (isLoading.patching = value),
@@ -162,15 +172,16 @@
},
onComplete: async (summary) => {
let resolvedSummary = summary;
- try {
- resolvedSummary = await stabilizeFailedVulnerabilitySummary(
- summary.imageId,
- summary,
- (id) => vulnerabilityService.getScanSummary(id),
- { scanRequestedAt: lastScanRequestedAt ?? vulnerabilityScan?.scanTime }
- );
- } catch {
+ const operationResult = await tryCatch(
+ (async () =>
+ stabilizeFailedVulnerabilitySummary(summary.imageId, summary, (id) => vulnerabilityService.getScanSummary(id), {
+ scanRequestedAt: lastScanRequestedAt ?? vulnerabilityScan?.scanTime
+ }))()
+ );
+ if (operationResult.error !== null) {
// Keep original summary when stabilization check fails.
+ } else {
+ resolvedSummary = operationResult.data;
}
if (isVulnerabilityScanInProgress(resolvedSummary.status)) {
@@ -189,9 +200,10 @@
}
stopPolling();
- try {
- vulnerabilityScan = await vulnerabilityService.getScanResult(resolvedSummary.imageId);
- } catch (error) {
+ const operationResult2 = await tryCatch((async () => vulnerabilityService.getScanResult(resolvedSummary.imageId))());
+ if (operationResult2.error !== null) {
+ const error = operationResult2.error;
+
console.error('Failed to load scan result:', error);
vulnerabilityScan = {
...(vulnerabilityScan ?? {}),
@@ -202,6 +214,8 @@
summary: resolvedSummary.summary,
error: resolvedSummary.error
} as VulnerabilityScanResult;
+ } else {
+ vulnerabilityScan = operationResult2.data;
}
if (showToast) {
toastVulnerabilityScanStatus(resolvedSummary);
@@ -268,6 +282,7 @@
destructive: true,
action: async (checkboxStates) => {
const force = !!checkboxStates['force'];
+ isLoading.removing = true;
await handleApiResultWithCallbacks({
result: await tryCatch(imageService.deleteImage(id, { force })),
message: m.failed_to_remove_image(),
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.ts b/frontend/src/routes/(app)/images/[imageId]/+page.ts
index f3597ec6d..2f12fe422 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.ts
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { imageService } from '#lib/services/image-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ImageDetailSummaryDto } from '#lib/types/docker.js';
@@ -17,35 +18,42 @@ export const load: PageLoad = async ({ params, parent }): Promise<ImageDetailDat
const { imageId } = params;
- try {
- const image = await queryClient.fetchQuery({
- queryKey: queryKeys.images.detail(envId, imageId),
- queryFn: () => imageService.getImageForEnvironment(envId, imageId)
- });
+ const operationResult = await tryCatch(
+ (async () => {
+ const image = await queryClient.fetchQuery({
+ queryKey: queryKeys.images.detail(envId, imageId),
+ queryFn: () => imageService.getImageForEnvironment(envId, imageId)
+ });
- if (!image) {
- throw error(404, 'Image not found');
- }
-
- let repo = '<none>';
- let tag = '<none>';
- const rawTags = image.repoTags ?? image.RepoTags;
- if (rawTags && rawTags.length > 0 && rawTags[0] !== '<none>:<none>') {
- ({ repo, tag } = parseImageRef(rawTags[0]));
- }
+ if (!image) {
+ throw error(404, 'Image not found');
+ }
- return {
- image: {
- ...image,
- repo,
- tag
+ let repo = '<none>';
+ let tag = '<none>';
+ const rawTags = image.repoTags ?? image.RepoTags;
+ if (rawTags && rawTags.length > 0 && rawTags[0] !== '<none>:<none>') {
+ ({ repo, tag } = parseImageRef(rawTags[0]));
}
- };
- } catch (err: any) {
+
+ return {
+ image: {
+ ...image,
+ repo,
+ tag
+ }
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
console.error('Failed to load image:', err);
- if (err.status === 404) {
+ if ('status' in err && err.status === 404) {
throw err;
}
throw error(500, err.message || 'Failed to load image details');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte b/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
index dbaa310c9..919b243cc 100644
--- a/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Card from '#lib/components/ui/card/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
@@ -23,10 +25,15 @@
loading = true;
error = null;
try {
- history = await imageService.getImageHistory(id);
- } catch (err) {
- console.error('Failed to load image history:', err);
- error = m.images_history_load_failed();
+ const operationResult = await tryCatch((async () => imageService.getImageHistory(id))());
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ console.error('Failed to load image history:', err);
+ error = m.images_history_load_failed();
+ } else {
+ history = operationResult.data;
+ }
} finally {
loading = false;
}
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index aada5e56a..fd406d8b4 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { onMount } from 'svelte';
import { z } from 'zod/v4';
import * as Tabs from '#lib/components/ui/tabs/index.js';
@@ -267,9 +269,13 @@
});
if (!response.ok || !response.body) {
- const errorData = (await response.json().catch(() => ({
- data: { message: m.build_request_failed() }
- }))) as Record<string, unknown>;
+ const errorData = (await tryCatch(response.json()).then((result) =>
+ result.error
+ ? {
+ data: { message: m.build_request_failed() }
+ }
+ : result.data
+ )) as Record<string, unknown>;
const errorDataPayload = errorData['data'] as Record<string, unknown> | undefined;
const errorMessage =
errorDataPayload?.['message'] ||
@@ -297,7 +303,12 @@
streamComplete = lines.some(handleBuildLine);
}
if (streamComplete) {
- await reader.cancel().catch(() => {});
+ await tryCatch(reader.cancel()).then((result) => {
+ if (result.error) {
+ return;
+ }
+ return result.data;
+ });
}
if (buildError) {
@@ -572,17 +583,24 @@
};
try {
- const resolvedEnvId = await environmentStore.getCurrentEnvironmentId();
- await buildMutation.mutateAsync({ envId: resolvedEnvId, ...payload });
- toast.success(m.build_completed());
- } catch (error) {
- const message = sanitizeLogText(error instanceof Error ? error.message : m.build_failed());
- buildError = message;
- buildStatusText = message.toLowerCase().startsWith(m.build_failed().toLowerCase())
- ? message
- : m.build_failed_with_error({ error: message });
- appendLog(m.build_error_log({ error: message }));
- toast.error(message);
+ const operationResult = await tryCatch(
+ (async () => {
+ const resolvedEnvId = await environmentStore.getCurrentEnvironmentId();
+ await buildMutation.mutateAsync({ envId: resolvedEnvId, ...payload });
+ toast.success(m.build_completed());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ const message = sanitizeLogText(error instanceof Error ? error.message : m.build_failed());
+ buildError = message;
+ buildStatusText = message.toLowerCase().startsWith(m.build_failed().toLowerCase())
+ ? message
+ : m.build_failed_with_error({ error: message });
+ appendLog(m.build_error_log({ error: message }));
+ toast.error(message);
+ }
} finally {
isBuilding = false;
}
diff --git a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
index 15b72aaf1..cb479021b 100644
--- a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
+++ b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import FileList from '#lib/components/file-browser/FileList.svelte';
import FileBreadcrumb from '#lib/components/file-browser/FileBreadcrumb.svelte';
import CreateFolderDialog from '#lib/components/file-browser/CreateFolderDialog.svelte';
@@ -172,15 +174,22 @@
if (!editorFile) return;
editorSaving = true;
try {
- const dirPath = editorFile.path.split('/').slice(0, -1).join('/') || '/';
- const file = new File([editorContent], editorFile.name, { type: 'text/plain' });
- await uploadMutation.mutateAsync({ path: dirPath, file });
- await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.content(envId, editorFile.path) });
- toast.success(m.common_file_saved());
- editorOpen = false;
- await filesQuery.refetch();
- } catch (e: any) {
- toast.error(e.message || 'Failed to save file');
+ const operationResult = await tryCatch(
+ (async () => {
+ const dirPath = editorFile.path.split('/').slice(0, -1).join('/') || '/';
+ const file = new File([editorContent], editorFile.name, { type: 'text/plain' });
+ await uploadMutation.mutateAsync({ path: dirPath, file });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.content(envId, editorFile.path) });
+ toast.success(m.common_file_saved());
+ editorOpen = false;
+ await filesQuery.refetch();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const e = operationResult.error;
+
+ toast.error(e.message || 'Failed to save file');
+ }
} finally {
editorSaving = false;
}
diff --git a/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte b/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte
index 7ebd591d9..a93e6b82e 100644
--- a/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte
+++ b/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import RepoTagFields from '#lib/components/form/repo-tag-fields.svelte';
@@ -43,16 +45,23 @@
isTagging = true;
try {
- await imageService.tagImage(imageId, {
- repository: data.repository.trim(),
- tag: data.tag?.trim() || undefined
- });
- toast.success(m.images_tag_success());
- await onTagged?.();
- handleOpenChange(false);
- } catch (error) {
- console.error('Failed to tag image:', error);
- toast.error(m.images_tag_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ await imageService.tagImage(imageId, {
+ repository: data.repository.trim(),
+ tag: data.tag?.trim() || undefined
+ });
+ toast.success(m.images_tag_success());
+ await onTagged?.();
+ handleOpenChange(false);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Failed to tag image:', error);
+ toast.error(m.images_tag_failed());
+ }
} finally {
isTagging = false;
}
diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelte
index ac0803c69..2f828c157 100644
--- a/frontend/src/routes/(app)/images/image-table.svelte
+++ b/frontend/src/routes/(app)/images/image-table.svelte
@@ -11,7 +11,7 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import ImageUpdateItem from '#lib/components/image-update-item.svelte';
import VulnerabilityScanItem from '#lib/components/vulnerability/vulnerability-scan-item.svelte';
import UniversalMobileCard from '#lib/components/arcane-table/cards/universal-mobile-card.svelte';
@@ -155,7 +155,7 @@
isLoading.removing = true;
const result = await tryCatch(imageService.deleteImage(id, { force }));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.failed_to_remove_image(),
setLoadingState: () => {},
@@ -177,7 +177,7 @@
}
const result = await tryCatch(imageService.pullImage(repoTag));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.images_pull_failed(),
setLoadingState: () => {},
@@ -190,7 +190,7 @@
async function handleInlineVulnerabilityScan(imageId: string) {
const result = await tryCatch(vulnerabilityService.scanImage(imageId));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.vuln_scan_failed(),
setLoadingState: () => {},
@@ -229,7 +229,7 @@
async function handleInlineImagePatch(imageId: string) {
const result = await tryCatch(imageService.patchImage(imageId));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.images_patch_failed(),
setLoadingState: () => {},
@@ -296,43 +296,49 @@
scanPollInFlight = true;
try {
- const response = await vulnerabilityService.getScanSummaries(imageIds);
- if (destroyed) return;
- const summaries = response?.summaries ?? {};
-
- if (Object.keys(summaries).length > 0 && images.data?.length) {
- let changed = false;
- let completed = false;
- const nextScanRequestedAtByImage = { ...scanRequestedAtByImage };
- const nextData = images.data.map((img) => {
- const summary = summaries[img.id];
- if (!summary) return img;
-
- if (
- summary.status === 'failed' &&
- isLikelyStaleFailedSummary(summary, nextScanRequestedAtByImage[img.id]) &&
- isVulnerabilityScanInProgress(img.vulnerabilityScan?.status)
- ) {
- return img;
- }
-
- changed = true;
- if (summary.status === 'completed' || summary.status === 'failed') {
- completed = true;
- delete nextScanRequestedAtByImage[img.id];
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await vulnerabilityService.getScanSummaries(imageIds);
+ if (destroyed) return;
+ const summaries = response?.summaries ?? {};
+
+ if (Object.keys(summaries).length > 0 && images.data?.length) {
+ let changed = false;
+ let completed = false;
+ const nextScanRequestedAtByImage = { ...scanRequestedAtByImage };
+ const nextData = images.data.map((img) => {
+ const summary = summaries[img.id];
+ if (!summary) return img;
+
+ if (
+ summary.status === 'failed' &&
+ isLikelyStaleFailedSummary(summary, nextScanRequestedAtByImage[img.id]) &&
+ isVulnerabilityScanInProgress(img.vulnerabilityScan?.status)
+ ) {
+ return img;
+ }
+
+ changed = true;
+ if (summary.status === 'completed' || summary.status === 'failed') {
+ completed = true;
+ delete nextScanRequestedAtByImage[img.id];
+ }
+ return { ...img, vulnerabilityScan: summary };
+ });
+ if (changed) {
+ images = { ...images, data: nextData };
+ scanRequestedAtByImage = nextScanRequestedAtByImage;
+ }
+ if (completed) {
+ await onImageUpdated?.();
+ }
}
- return { ...img, vulnerabilityScan: summary };
- });
- if (changed) {
- images = { ...images, data: nextData };
- scanRequestedAtByImage = nextScanRequestedAtByImage;
- }
- if (completed) {
- await onImageUpdated?.();
- }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Failed to poll vulnerability summaries:', error);
}
- } catch (error) {
- console.error('Failed to poll vulnerability summaries:', error);
} finally {
scanPollInFlight = false;
if (!destroyed && getScanningImageIds().length > 0) {
diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.ts
index 5c1f2569e..15c1fa417 100644
--- a/frontend/src/routes/(app)/networks/+page.ts
+++ b/frontend/src/routes/(app)/networks/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { networkService } from '#lib/services/network-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { resolveListPageLoadContext } from '#lib/utils/tables.js';
@@ -16,13 +17,19 @@ export const load: PageLoad = async ({ parent }) => {
// Single API call - counts are included in the response
let networks;
- try {
- networks = await queryClient.fetchQuery({
- queryKey: queryKeys.networks.list(envId, networkRequestOptions),
- queryFn: () => networkService.getNetworksForEnvironment(envId, networkRequestOptions)
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.networks.list(envId, networkRequestOptions),
+ queryFn: () => networkService.getNetworksForEnvironment(envId, networkRequestOptions)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load networks');
+ } else {
+ networks = operationResult.data;
}
return {
diff --git a/frontend/src/routes/(app)/networks/[networkId]/+page.svelte b/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
index e15fb6c17..4318cff34 100644
--- a/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
+++ b/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
@@ -23,7 +23,7 @@
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { goto } from '$app/navigation';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { m } from '#lib/paraglide/messages.js';
import { networkService } from '#lib/services/network-service.js';
import { ResourceDetailLayout, type DetailAction } from '#lib/layouts/index.js';
@@ -55,13 +55,19 @@
sortDir = newSortDir;
if (data.network?.id) {
- try {
- network = await networkService.getNetwork(data.network.id, {
- sort: { column: sortCol, direction: sortDir }
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ networkService.getNetwork(data.network.id, {
+ sort: { column: sortCol, direction: sortDir }
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
console.error('Failed to sort network containers:', err);
toast.error(m.common_action_failed());
+ } else {
+ network = operationResult.data;
}
}
}
@@ -85,7 +91,8 @@
label: m.common_remove(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isRemoving = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(networkService.deleteNetwork(network.id)),
message: m.networks_remove_failed({ name: network?.name ?? shortId }),
setLoadingState: (value) => (isRemoving = value),
diff --git a/frontend/src/routes/(app)/networks/[networkId]/+page.ts b/frontend/src/routes/(app)/networks/[networkId]/+page.ts
index 1516bf357..d080e1b8f 100644
--- a/frontend/src/routes/(app)/networks/[networkId]/+page.ts
+++ b/frontend/src/routes/(app)/networks/[networkId]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import { networkService } from '#lib/services/network-service.js';
@@ -10,24 +11,31 @@ export const load: PageLoad = async ({ params, parent }) => {
const { networkId } = params;
- try {
- const network = await queryClient.fetchQuery({
- queryKey: queryKeys.networks.detail(envId, networkId),
- queryFn: () => networkService.getNetworkForEnvironment(envId, networkId)
- });
+ const operationResult = await tryCatch(
+ (async () => {
+ const network = await queryClient.fetchQuery({
+ queryKey: queryKeys.networks.detail(envId, networkId),
+ queryFn: () => networkService.getNetworkForEnvironment(envId, networkId)
+ });
- if (!network) {
- throw error(404, 'Network not found');
- }
+ if (!network) {
+ throw error(404, 'Network not found');
+ }
+
+ return {
+ network
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- return {
- network
- };
- } catch (err: any) {
console.error('Failed to load network:', err);
- if (err.status === 404) {
+ if ('status' in err && err.status === 404) {
throw err;
}
throw error(500, err.message || 'Failed to load network details');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/networks/network-table.svelte b/frontend/src/routes/(app)/networks/network-table.svelte
index c5bfb30d9..c7eb6a652 100644
--- a/frontend/src/routes/(app)/networks/network-table.svelte
+++ b/frontend/src/routes/(app)/networks/network-table.svelte
@@ -8,7 +8,7 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { DEFAULT_NETWORK_NAMES } from '#lib/constants.js';
import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
@@ -66,7 +66,8 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isLoading.remove = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(networkService.deleteNetwork(id)),
message: m.common_delete_failed({ resource: `${m.resource_network()} "${safeName}"` }),
setLoadingState: (value) => (isLoading.remove = value),
diff --git a/frontend/src/routes/(app)/networks/ports/+page.ts b/frontend/src/routes/(app)/networks/ports/+page.ts
index d10973fe7..b5a81ca95 100644
--- a/frontend/src/routes/(app)/networks/ports/+page.ts
+++ b/frontend/src/routes/(app)/networks/ports/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { portService } from '#lib/services/port-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { resolveListPageLoadContext } from '#lib/utils/tables.js';
@@ -15,13 +16,19 @@ export const load: PageLoad = async ({ parent }) => {
});
let ports;
- try {
- ports = await queryClient.fetchQuery({
- queryKey: queryKeys.ports.list(envId, portRequestOptions),
- queryFn: () => portService.getPortsForEnvironment(envId, portRequestOptions)
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.ports.list(envId, portRequestOptions),
+ queryFn: () => portService.getPortsForEnvironment(envId, portRequestOptions)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load ports');
+ } else {
+ ports = operationResult.data;
}
return {
diff --git a/frontend/src/routes/(app)/networks/topology/+page.ts b/frontend/src/routes/(app)/networks/topology/+page.ts
index e7d74ba8c..1c8f5971a 100644
--- a/frontend/src/routes/(app)/networks/topology/+page.ts
+++ b/frontend/src/routes/(app)/networks/topology/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { networkService } from '#lib/services/network-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { throwPageLoadError } from '#lib/utils/api.js';
@@ -9,13 +10,19 @@ export const load: PageLoad = async ({ parent }) => {
const envId = await environmentStore.getCurrentEnvironmentId();
let topology;
- try {
- topology = await queryClient.fetchQuery({
- queryKey: queryKeys.networks.topology(envId),
- queryFn: () => networkService.getNetworkTopology(envId)
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.networks.topology(envId),
+ queryFn: () => networkService.getNetworkTopology(envId)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load network topology');
+ } else {
+ topology = operationResult.data;
}
return {
diff --git a/frontend/src/routes/(app)/projects/+page.ts b/frontend/src/routes/(app)/projects/+page.ts
index 5ef6a8db8..8cb4aa05c 100644
--- a/frontend/src/routes/(app)/projects/+page.ts
+++ b/frontend/src/routes/(app)/projects/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { projectService } from '#lib/services/project-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -32,23 +33,29 @@ export const load: PageLoad = async ({ parent, url }) => {
let projects;
let projectStatusCounts;
let projectTags;
- try {
- [projects, projectStatusCounts, projectTags] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.projects.list(envId, projectRequestOptions),
- queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.projects.statusCounts(envId),
- queryFn: () => projectService.getProjectStatusCountsForEnvironment(envId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.projects.tags(envId),
- queryFn: () => projectService.getProjectTagsForEnvironment(envId)
- })
- ]);
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.projects.list(envId, projectRequestOptions),
+ queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.projects.statusCounts(envId),
+ queryFn: () => projectService.getProjectStatusCountsForEnvironment(envId)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.projects.tags(envId),
+ queryFn: () => projectService.getProjectTagsForEnvironment(envId)
+ })
+ ]))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load projects');
+ } else {
+ [projects, projectStatusCounts, projectTags] = operationResult.data;
}
return { envId, projects, projectRequestOptions, projectStatusCounts, projectTags, showArchived };
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index daabfb50d..4a1202bf5 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -30,7 +30,7 @@
import { page } from '$app/state';
import { mode } from 'mode-watcher';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { z } from 'zod/v4';
import { createForm } from '#lib/utils/settings.js';
@@ -757,47 +757,57 @@
let workspaceCommitted = false;
isLoading.saving = true;
try {
- if (workspaceUpdate.fileChanges.length > 0) {
- const workspace = await projectWorkspaceService.updateWorkspace(
- projectId,
- {
- fileTreeRevision: projectWorkspaceQuery.data?.fileTreeRevision ?? '',
- fileChanges: workspaceUpdate.fileChanges
- },
- workspaceUpdate.files,
- envId
- );
- workspaceCommitted = true;
- queryClient.setQueryData(queryKeys.projects.workspace(envId, projectId), workspace);
-
- loadedProjectWorkspaceContents = { ...loadedProjectWorkspaceContents, ...projectWorkspaceContents };
- loadedIncludeFileContents = {
- ...loadedIncludeFileContents,
- ...Object.fromEntries(
- changedIncludeFilePaths.flatMap((relativePath) => {
- const content = includeFilesState[relativePath];
- return content === undefined ? [] : [[relativePath, content] as const];
- })
- )
- };
- projectWorkspaceChanges = [];
- projectWorkspaceStagedFiles = {};
- projectWorkspaceStagedUploadedText = {};
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ if (workspaceUpdate.fileChanges.length > 0) {
+ const workspace = await projectWorkspaceService.updateWorkspace(
+ projectId,
+ {
+ fileTreeRevision: projectWorkspaceQuery.data?.fileTreeRevision ?? '',
+ fileChanges: workspaceUpdate.fileChanges
+ },
+ workspaceUpdate.files,
+ envId
+ );
+ workspaceCommitted = true;
+ queryClient.setQueryData(queryKeys.projects.workspace(envId, projectId), workspace);
+
+ loadedProjectWorkspaceContents = { ...loadedProjectWorkspaceContents, ...projectWorkspaceContents };
+ loadedIncludeFileContents = {
+ ...loadedIncludeFileContents,
+ ...Object.fromEntries(
+ changedIncludeFilePaths.flatMap((relativePath) => {
+ const content = includeFilesState[relativePath];
+ return content === undefined ? [] : [[relativePath, content] as const];
+ })
+ )
+ };
+ projectWorkspaceChanges = [];
+ projectWorkspaceStagedFiles = {};
+ projectWorkspaceStagedUploadedText = {};
+ }
- const updatedProject = await projectService.updateProject(
- projectId,
- namePayload,
- composePayload,
- envPayload,
- overridePayload
+ const updatedProject = await projectService.updateProject(
+ projectId,
+ namePayload,
+ composePayload,
+ envPayload,
+ overridePayload
+ );
+ rebaseEditorDraft(updatedProject, { preserveProjectWorkspaceContents: true });
+ await syncProjectQueries(updatedProject);
+ toast.success(
+ m.common_update_success({ resource: m.project() }),
+ activityToastOptions(extractActivityId(updatedProject))
+ );
+ })()
);
- rebaseEditorDraft(updatedProject, { preserveProjectWorkspaceContents: true });
- await syncProjectQueries(updatedProject);
- toast.success(m.common_update_success({ resource: m.project() }), activityToastOptions(extractActivityId(updatedProject)));
- } catch (error) {
- const message = error instanceof Error ? error.message : m.common_save_failed();
- toast.error(workspaceCommitted ? m.projects_workspace_saved_configuration_failed({ error: message }) : message);
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ const message = error instanceof Error ? error.message : m.common_save_failed();
+ toast.error(workspaceCommitted ? m.projects_workspace_saved_configuration_failed({ error: message }) : message);
+ }
} finally {
isLoading.saving = false;
}
@@ -1089,14 +1099,21 @@
projectWorkspaceLoadErrors = removeWorkspaceFileRecord(projectWorkspaceLoadErrors, relativePath);
try {
- const file = await getProjectWorkspaceFileResource('workspace', relativePath);
- projectWorkspaceFileMetadata = { ...projectWorkspaceFileMetadata, [relativePath]: file };
- if (file.editable) updateLoadedProjectWorkspaceFile(relativePath, file.content ?? '');
- } catch (error) {
- projectWorkspaceLoadErrors = {
- ...projectWorkspaceLoadErrors,
- [relativePath]: error instanceof Error ? error.message : String(error)
- };
+ const operationResult = await tryCatch(
+ (async () => {
+ const file = await getProjectWorkspaceFileResource('workspace', relativePath);
+ projectWorkspaceFileMetadata = { ...projectWorkspaceFileMetadata, [relativePath]: file };
+ if (file.editable) updateLoadedProjectWorkspaceFile(relativePath, file.content ?? '');
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ projectWorkspaceLoadErrors = {
+ ...projectWorkspaceLoadErrors,
+ [relativePath]: error instanceof Error ? error.message : String(error)
+ };
+ }
} finally {
projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);
}
@@ -1125,12 +1142,19 @@
projectWorkspaceLoadErrors = removeWorkspaceFileRecord(projectWorkspaceLoadErrors, relativePath);
try {
- await getProjectWorkspaceFileResource(kind, relativePath);
- } catch (error) {
- projectWorkspaceLoadErrors = {
- ...projectWorkspaceLoadErrors,
- [relativePath]: error instanceof Error ? error.message : String(error)
- };
+ const operationResult = await tryCatch(
+ (async () => {
+ await getProjectWorkspaceFileResource(kind, relativePath);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ projectWorkspaceLoadErrors = {
+ ...projectWorkspaceLoadErrors,
+ [relativePath]: error instanceof Error ? error.message : String(error)
+ };
+ }
} finally {
projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);
}
@@ -1251,9 +1275,14 @@
}
async function downloadProjectWorkspaceFile(relativePath: string) {
- try {
- await projectWorkspaceService.downloadWorkspaceFile(projectId, relativePath, envId);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await projectWorkspaceService.downloadWorkspaceFile(projectId, relativePath, envId);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.common_download_error());
}
}
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.ts b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
index abb2dc8b6..992a87caf 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.ts
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { projectService } from '#lib/services/project-service.js';
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
import { variableService } from '#lib/services/variable-service.js';
@@ -8,15 +9,20 @@ import type { QueryClient } from '@tanstack/svelte-query';
import type { PageLoad } from './$types';
async function loadGlobalVariables(queryClient: QueryClient) {
- return queryClient
- .fetchQuery({
+ return tryCatch(
+ queryClient.fetchQuery({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
- .catch((err) => {
+ ).then((result) => {
+ if (result.error) {
+ const err: Error = result.error;
+
console.warn('Failed to load global variables:', err);
return [];
- });
+ }
+ return result.data;
+ });
}
export const load: PageLoad = async ({ params, parent }) => {
@@ -26,13 +32,19 @@ export const load: PageLoad = async ({ params, parent }) => {
type ProjectData = Awaited<ReturnType<typeof projectService.getProjectForEnvironment>>;
let project: ProjectData;
- try {
- project = await queryClient.fetchQuery({
- queryKey: queryKeys.projects.detail(envId, params.projectId),
- queryFn: () => projectService.getProjectForEnvironment(envId, params.projectId)
- });
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ queryClient.fetchQuery({
+ queryKey: queryKeys.projects.detail(envId, params.projectId),
+ queryFn: () => projectService.getProjectForEnvironment(envId, params.projectId)
+ }))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load project');
+ } else {
+ project = operationResult.data;
}
// Kick off the file-tree walk without awaiting it: on large projects it can
diff --git a/frontend/src/routes/(app)/projects/components/ProjectServicesPanel.svelte b/frontend/src/routes/(app)/projects/components/ProjectServicesPanel.svelte
index 0ae41d1e4..7cd9888ea 100644
--- a/frontend/src/routes/(app)/projects/components/ProjectServicesPanel.svelte
+++ b/frontend/src/routes/(app)/projects/components/ProjectServicesPanel.svelte
@@ -16,7 +16,8 @@
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
import { toast } from 'svelte-sonner';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { confirmAndRemoveContainer, runContainerLifecycleAction } from '#lib/utils/container-actions.js';
import { cn } from '#lib/utils.js';
@@ -107,19 +108,24 @@
const id = item.id;
actionStatus[id] = 'restarting';
- try {
- handleApiResultWithCallbacks({
- result: await tryCatch(projectService.restartProject(projectId, [item.name])),
- message: m.containers_restart_failed(),
- setLoadingState: (value) => {
- actionStatus[id] = value ? 'restarting' : '';
- },
- async onSuccess(data) {
- toast.success(m.containers_restart_success(), activityToastOptions(extractActivityId(data)));
- await onRefresh?.();
- }
- });
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(projectService.restartProject(projectId, [item.name])),
+ message: m.containers_restart_failed(),
+ setLoadingState: (value) => {
+ actionStatus[id] = value ? 'restarting' : '';
+ },
+ async onSuccess(data) {
+ toast.success(m.containers_restart_success(), activityToastOptions(extractActivityId(data)));
+ await onRefresh?.();
+ }
+ });
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Service restart failed:', error);
toast.error(m.containers_action_error());
actionStatus[id] = '';
diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index 8f8227b98..a25053bd4 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -17,7 +17,8 @@
import { hasPermission } from '#lib/utils/auth.js';
import { containerService } from '#lib/services/container-service.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
- import { extractApiErrorMessage, tryCatch } from '#lib/utils/api.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { ComposeEditorSplit } from '#lib/components/compose/index.js';
import ResizableSplit from '#lib/components/resizable-split.svelte';
import { Switch } from '#lib/components/ui/switch/index.js';
diff --git a/frontend/src/routes/(app)/projects/new/+page.ts b/frontend/src/routes/(app)/projects/new/+page.ts
index 16336a39a..b48a7f0dd 100644
--- a/frontend/src/routes/(app)/projects/new/+page.ts
+++ b/frontend/src/routes/(app)/projects/new/+page.ts
@@ -1,6 +1,7 @@
import { parse } from 'yaml';
import { containerService } from '#lib/services/container-service.js';
-import { throwPageLoadError, tryCatch } from '#lib/utils/api.js';
+import { throwPageLoadError } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { loadTemplateAuthoringData, loadTemplateContent } from '#lib/utils/template-load.js';
import type { PageLoad } from './$types';
diff --git a/frontend/src/routes/(app)/projects/projects-table.actions.ts b/frontend/src/routes/(app)/projects/projects-table.actions.ts
index d03a6764d..182c12d5a 100644
--- a/frontend/src/routes/(app)/projects/projects-table.actions.ts
+++ b/frontend/src/routes/(app)/projects/projects-table.actions.ts
@@ -5,7 +5,7 @@ import { gitOpsSyncService } from '#lib/services/gitops-sync-service.js';
import { projectService } from '#lib/services/project-service.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
-import { tryCatch } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import type { TableActionConfig, TableBulkActionConfig } from '#lib/utils/table-action-types.js';
import { toast } from 'svelte-sonner';
@@ -103,19 +103,22 @@ export function createProjectActions({
const config = projectActionConfigs[action];
actionStatus[id] = config.status;
- try {
- await handleApiResultWithCallbacks({
- result: await tryCatch(config.run(id)),
- message: config.failure(),
- setLoadingState: (value) => {
- actionStatus[id] = value ? config.status : '';
- },
- onSuccess: async (data) => {
- toast.success(config.success(), activityToastOptions(extractActivityId(data)));
- await refreshProjects();
- }
- });
- } catch {
+ const operationResult = await tryCatch(
+ (async () => {
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(config.run(id)),
+ message: config.failure(),
+ setLoadingState: (value) => {
+ actionStatus[id] = value ? config.status : '';
+ },
+ onSuccess: async (data) => {
+ toast.success(config.success(), activityToastOptions(extractActivityId(data)));
+ await refreshProjects();
+ }
+ });
+ })()
+ );
+ if (operationResult.error !== null) {
toast.error(m.common_action_failed());
actionStatus[id] = '';
}
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index 6029b9b40..85b15eedb 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import type { Project, ProjectTagColor, ProjectTagOption } from '#lib/types/swarm.js';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
@@ -91,19 +93,24 @@
};
try {
- const results = await imageService.checkMultipleImages(imageRefs);
- const firstError = Object.values(results)
- .find((result) => !!result?.error?.trim())
- ?.error?.trim();
- const hasErrors = !!firstError;
- if (hasErrors) {
- toast.error(firstError || m.containers_check_updates_failed());
- } else {
- toast.success(m.images_update_check_completed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const results = await imageService.checkMultipleImages(imageRefs);
+ const firstError = Object.values(results)
+ .find((result) => !!result?.error?.trim())
+ ?.error?.trim();
+ const hasErrors = !!firstError;
+ if (hasErrors) {
+ toast.error(firstError || m.containers_check_updates_failed());
+ } else {
+ toast.success(m.images_update_check_completed());
+ }
+ await refreshProjects(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ toast.error(m.containers_check_updates_failed());
}
- await refreshProjects(requestOptions);
- } catch {
- toast.error(m.containers_check_updates_failed());
} finally {
checkingProjectIds = {
...checkingProjectIds,
diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelte
index a2d41b38a..6c4bba0c6 100644
--- a/frontend/src/routes/(app)/security/+page.svelte
+++ b/frontend/src/routes/(app)/security/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ResourcePageLayout, type ActionButton } from '#lib/layouts/index.js';
import { m } from '#lib/paraglide/messages.js';
import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
@@ -70,10 +72,15 @@
});
let patchRequestOptions = $derived<SearchPaginationSortRequest>(data.patchRequestOptions);
async function loadPatches() {
- try {
- const response = await imageService.listPatchTargets(patchRequestOptions);
- patchTargets = { ...response, data: (response.data ?? []).map((t) => ({ ...t, id: t.imageId })) };
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await imageService.listPatchTargets(patchRequestOptions);
+ patchTargets = { ...response, data: (response.data ?? []).map((t) => ({ ...t, id: t.imageId })) };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to load image patch targets:', error);
toast.error(m.common_refresh_failed({ resource: m.patches() }));
}
@@ -226,58 +233,69 @@
scanProgress = { current: 0, total: 0 };
try {
- // Fetch all images with a high limit to get all of them
- const imagesResponse = await imageService.getImages({ pagination: { page: 1, limit: 1000 } });
- const images = imagesResponse.data ?? [];
-
- if (images.length === 0) {
- toast.info(m.security_no_images_to_scan());
- isLoading.scanningAll = false;
- return;
+ const operationResult = await tryCatch(
+ (async () => {
+ // Fetch all images with a high limit to get all of them
+ const imagesResponse = await imageService.getImages({ pagination: { page: 1, limit: 1000 } });
+ const images = imagesResponse.data ?? [];
+
+ if (images.length === 0) {
+ toast.info(m.security_no_images_to_scan());
+ isLoading.scanningAll = false;
+ return;
+ }
+
+ scanProgress = { current: 0, total: images.length };
+
+ const BATCH_SIZE = 3;
+ let succeeded = 0;
+ let failed = 0;
+
+ for (let i = 0; i < images.length; i += BATCH_SIZE) {
+ const batch = images.slice(i, i + BATCH_SIZE);
+
+ await Promise.all(
+ batch.map(async (image) => {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await vulnerabilityService.scanImage(image.id);
+ if (result.status === 'completed' || result.status === 'scanning' || result.status === 'pending') {
+ succeeded++;
+ } else {
+ failed++;
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error(`Failed to scan image ${image.id}:`, error);
+ failed++;
+ }
+ scanProgress.current++;
+ })
+ );
+ }
+
+ // Show summary toast (scans run in background; this reflects requests started, not completed)
+ if (failed === 0) {
+ toast.success(m.security_scan_all_success({ count: succeeded }));
+ } else if (succeeded === 0) {
+ toast.error(m.security_scan_all_failed({ count: failed }));
+ } else {
+ toast.warning(m.security_scan_all_partial({ succeeded, failed }));
+ }
+
+ // Refresh the vulnerability data and keep polling for updates as scans complete
+ await refreshAll();
+ startScanPolling(images.length);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Error during scan all:', error);
+ toast.error(m.security_scan_all_error());
}
-
- scanProgress = { current: 0, total: images.length };
-
- const BATCH_SIZE = 3;
- let succeeded = 0;
- let failed = 0;
-
- for (let i = 0; i < images.length; i += BATCH_SIZE) {
- const batch = images.slice(i, i + BATCH_SIZE);
-
- await Promise.all(
- batch.map(async (image) => {
- try {
- const result = await vulnerabilityService.scanImage(image.id);
- if (result.status === 'completed' || result.status === 'scanning' || result.status === 'pending') {
- succeeded++;
- } else {
- failed++;
- }
- } catch (error) {
- console.error(`Failed to scan image ${image.id}:`, error);
- failed++;
- }
- scanProgress.current++;
- })
- );
- }
-
- // Show summary toast (scans run in background; this reflects requests started, not completed)
- if (failed === 0) {
- toast.success(m.security_scan_all_success({ count: succeeded }));
- } else if (succeeded === 0) {
- toast.error(m.security_scan_all_failed({ count: failed }));
- } else {
- toast.warning(m.security_scan_all_partial({ succeeded, failed }));
- }
-
- // Refresh the vulnerability data and keep polling for updates as scans complete
- await refreshAll();
- startScanPolling(images.length);
- } catch (error) {
- console.error('Error during scan all:', error);
- toast.error(m.security_scan_all_error());
} finally {
isLoading.scanningAll = false;
scanProgress = { current: 0, total: 0 };
diff --git a/frontend/src/routes/(app)/security/+page.ts b/frontend/src/routes/(app)/security/+page.ts
index 705b12331..584221ed3 100644
--- a/frontend/src/routes/(app)/security/+page.ts
+++ b/frontend/src/routes/(app)/security/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -37,19 +38,25 @@ export const load: PageLoad = async ({ parent }) => {
let summary;
let vulnerabilities;
- try {
- [summary, vulnerabilities] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.vulnerabilities.summaryByEnvironment(envId),
- queryFn: () => vulnerabilityService.getEnvironmentSummaryForEnvironment(envId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.vulnerabilities.allByEnvironment(envId, requestForApi),
- queryFn: () => vulnerabilityService.getAllVulnerabilitiesForEnvironment(envId, requestForApi)
- })
- ]);
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.vulnerabilities.summaryByEnvironment(envId),
+ queryFn: () => vulnerabilityService.getEnvironmentSummaryForEnvironment(envId)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.vulnerabilities.allByEnvironment(envId, requestForApi),
+ queryFn: () => vulnerabilityService.getAllVulnerabilitiesForEnvironment(envId, requestForApi)
+ })
+ ]))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load security data');
+ } else {
+ [summary, vulnerabilities] = operationResult.data;
}
return {
diff --git a/frontend/src/routes/(app)/security/security-patch-table.svelte b/frontend/src/routes/(app)/security/security-patch-table.svelte
index 71e83cc1f..16a34c37f 100644
--- a/frontend/src/routes/(app)/security/security-patch-table.svelte
+++ b/frontend/src/routes/(app)/security/security-patch-table.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
@@ -44,12 +46,17 @@
}
async function handlePatchImage(item: PatchTargetRow) {
- try {
- // The fixable counts come from the stored scan, so patch from that report.
- const record = await imageService.patchImage(item.imageId, { scanId: item.imageId });
- toast.info(m.images_patch_started({ patchedRef: record.patchedRef }), activityToastOptions(record.activityId));
- await refreshPatchTargets(requestOptions);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ // The fixable counts come from the stored scan, so patch from that report.
+ const record = await imageService.patchImage(item.imageId, { scanId: item.imageId });
+ toast.info(m.images_patch_started({ patchedRef: record.patchedRef }), activityToastOptions(record.activityId));
+ await refreshPatchTargets(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to patch image:', error);
toast.error(m.images_patch_failed());
}
diff --git a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
index 53baeb5ec..ae05bf58c 100644
--- a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
+++ b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
// Patching happens on the Patches tab, per image; CVE rows only inspect and ignore.
@@ -56,12 +58,18 @@
}
async function handleUnignoreVulnerability(item: VulnerabilityRow) {
- if (!item.ignoreId) return;
- try {
- await vulnerabilityService.unignoreVulnerability(item.ignoreId);
- toast.success(m.vuln_unignore_success());
- await refreshVulnerabilityTable(requestOptions);
- } catch (error) {
+ const ignoreId = item.ignoreId;
+ if (!ignoreId) return;
+ const operationResult = await tryCatch(
+ (async () => {
+ await vulnerabilityService.unignoreVulnerability(ignoreId);
+ toast.success(m.vuln_unignore_success());
+ await refreshVulnerabilityTable(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to unignore vulnerability:', error);
toast.error(m.vuln_unignore_failed());
}
@@ -77,13 +85,20 @@
filters: severity ? { severity } : undefined
};
- try {
- const optionsResponse = await vulnerabilityService.getAllVulnerabilityImageOptions(request);
- imageNameFilterOptions = optionsResponse;
- return optionsResponse;
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const optionsResponse = await vulnerabilityService.getAllVulnerabilityImageOptions(request);
+ imageNameFilterOptions = optionsResponse;
+ return optionsResponse;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to refresh vulnerability image filter options:', error);
return imageNameFilterOptions;
+ } else {
+ return operationResult.data;
}
}
@@ -111,19 +126,24 @@
pkgName: item.pkgName,
installedVersion: item.installedVersion
});
- try {
- const payload = {
- imageId: item.imageId || '',
- vulnerabilityId: item.vulnerabilityId || '',
- pkgName: item.pkgName || '',
- installedVersion: item.installedVersion || ''
- };
- console.log('Sending payload:', payload);
- await vulnerabilityService.ignoreVulnerability(payload);
- toast.success(m.vuln_ignore_success({ cve: item.vulnerabilityId }));
- // Refresh the table to remove the ignored vulnerability
- await refreshVulnerabilityTable(requestOptions);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const payload = {
+ imageId: item.imageId || '',
+ vulnerabilityId: item.vulnerabilityId || '',
+ pkgName: item.pkgName || '',
+ installedVersion: item.installedVersion || ''
+ };
+ console.log('Sending payload:', payload);
+ await vulnerabilityService.ignoreVulnerability(payload);
+ toast.success(m.vuln_ignore_success({ cve: item.vulnerabilityId }));
+ // Refresh the table to remove the ignored vulnerability
+ await refreshVulnerabilityTable(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to ignore vulnerability:', error);
toast.error(m.vuln_ignore_failed());
}
diff --git a/frontend/src/routes/(app)/settings/+layout.ts b/frontend/src/routes/(app)/settings/+layout.ts
index 388edbc6b..3c96c5c95 100644
--- a/frontend/src/routes/(app)/settings/+layout.ts
+++ b/frontend/src/routes/(app)/settings/+layout.ts
@@ -1,16 +1,24 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { settingsService } from '#lib/services/settings-service.js';
export const load = async ({ parent }) => {
- try {
- const { settings } = await parent();
- const oidcStatus = await settingsService.getOidcStatus();
+ const operationResult = await tryCatch(
+ (async () => {
+ const { settings } = await parent();
+ const oidcStatus = await settingsService.getOidcStatus();
+
+ return {
+ settings,
+ oidcStatus
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- return {
- settings,
- oidcStatus
- };
- } catch (error) {
console.error('Failed to load OIDC status:', error);
throw error;
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/settings/+page.svelte b/frontend/src/routes/(app)/settings/+page.svelte
index 74568e617..26eeb04a0 100644
--- a/frontend/src/routes/(app)/settings/+page.svelte
+++ b/frontend/src/routes/(app)/settings/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import type { PageProps } from './$types';
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
@@ -99,12 +101,17 @@
} as const;
onMount(async () => {
- try {
- settingsCategories = orderCategoriesByNav(
- (await settingsSearchService.getCategories()).filter(isAccessibleCategory),
- getSettingsSubpageUrlsInNavOrder()
- );
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ settingsCategories = orderCategoriesByNav(
+ (await settingsSearchService.getCategories()).filter(isAccessibleCategory),
+ getSettingsSubpageUrlsInNavOrder()
+ );
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to load categories:', error);
}
});
diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.svelte b/frontend/src/routes/(app)/settings/api-keys/+page.svelte
index 12d525e84..098e500e6 100644
--- a/frontend/src/routes/(app)/settings/api-keys/+page.svelte
+++ b/frontend/src/routes/(app)/settings/api-keys/+page.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import ApiKeyTable from './api-key-table.svelte';
import ApiKeyFormSheet from '#lib/components/sheets/api-key-form-sheet.svelte';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -57,38 +57,43 @@
const loading = isEditMode ? 'editing' : 'creating';
isLoading[loading] = true;
- try {
- if (isEditMode && apiKeyId) {
- const safeName = apiKey.name?.trim() || 'Unknown';
- const result = await tryCatch(apiKeyService.update(apiKeyId, apiKey));
- handleApiResultWithCallbacks({
- result,
- message: m.api_key_update_failed({ name: safeName }),
- setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async () => {
- toast.success(m.api_key_updated_success({ name: safeName }));
- apiKeys = await apiKeyService.getApiKeys(requestOptions);
- isDialogOpen.edit = false;
- apiKeyToEdit = null;
- }
- });
- } else {
- const safeName = apiKey.name?.trim() || 'Unknown';
- const result = await tryCatch(apiKeyService.create({ ...apiKey, permissions: apiKey.permissions ?? [] }));
- handleApiResultWithCallbacks({
- result,
- message: m.api_key_create_failed({ name: safeName }),
- setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async (createdKey) => {
- toast.success(m.api_key_created_success({ name: safeName }));
- apiKeys = await apiKeyService.getApiKeys(requestOptions);
- isDialogOpen.create = false;
- newlyCreatedKey = createdKey as ApiKeyCreated;
- isDialogOpen.showKey = true;
- }
- });
- }
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ if (isEditMode && apiKeyId) {
+ const safeName = apiKey.name?.trim() || 'Unknown';
+ const result = await tryCatch(apiKeyService.update(apiKeyId, apiKey));
+ await handleApiResultWithCallbacks({
+ result,
+ message: m.api_key_update_failed({ name: safeName }),
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async () => {
+ toast.success(m.api_key_updated_success({ name: safeName }));
+ apiKeys = await apiKeyService.getApiKeys(requestOptions);
+ isDialogOpen.edit = false;
+ apiKeyToEdit = null;
+ }
+ });
+ } else {
+ const safeName = apiKey.name?.trim() || 'Unknown';
+ const result = await tryCatch(apiKeyService.create({ ...apiKey, permissions: apiKey.permissions ?? [] }));
+ await handleApiResultWithCallbacks({
+ result,
+ message: m.api_key_create_failed({ name: safeName }),
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async (createdKey) => {
+ toast.success(m.api_key_created_success({ name: safeName }));
+ apiKeys = await apiKeyService.getApiKeys(requestOptions);
+ isDialogOpen.create = false;
+ newlyCreatedKey = createdKey as ApiKeyCreated;
+ isDialogOpen.showKey = true;
+ }
+ });
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to submit API key:', error);
}
}
diff --git a/frontend/src/routes/(app)/settings/authentication/+page.svelte b/frontend/src/routes/(app)/settings/authentication/+page.svelte
index 52e156256..1c9f97374 100644
--- a/frontend/src/routes/(app)/settings/authentication/+page.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/+page.svelte
@@ -28,7 +28,7 @@
import type { OidcRoleMapping, CreateOidcRoleMapping, UpdateOidcRoleMapping } from '#lib/types/auth.js';
import { oidcMappingService } from '#lib/services/oidc-mapping-service.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import IfPermitted from '#lib/components/if-permitted.svelte';
import { mergeProps } from 'bits-ui';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
@@ -90,7 +90,7 @@
if (editingMapping) {
const id = editingMapping.id;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(oidcMappingService.update(id, payload)),
message: m.common_update_failed({ resource: m.resource_oidc_mapping() }),
setLoadingState: (v) => (mappingSaving = v),
@@ -102,7 +102,7 @@
}
});
} else {
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(oidcMappingService.create(payload)),
message: m.common_create_failed({ resource: m.resource_oidc_mapping() }),
setLoadingState: (v) => (mappingSaving = v),
@@ -238,27 +238,34 @@
settingsForm.setLoading(true);
try {
- await settingsForm.updateSettings({
- authLocalEnabled: formData.authLocalEnabled,
- authSessionTimeout: formData.authSessionTimeout,
- authPasswordPolicy: formData.authPasswordPolicy,
- oidcEnabled: formData.oidcEnabled,
- oidcMergeAccounts: formData.oidcMergeAccounts,
- oidcSkipTlsVerify: formData.oidcSkipTlsVerify,
- oidcAutoRedirectToProvider: formData.oidcAutoRedirectToProvider,
- oidcClientId: formData.oidcClientId,
- oidcIssuerUrl: formData.oidcIssuerUrl,
- oidcScopes: formData.oidcScopes,
- oidcGroupsClaim: formData.oidcGroupsClaim,
- oidcProviderName: formData.oidcProviderName,
- oidcProviderLogoUrl: formData.oidcProviderLogoUrl,
- ...(formData.oidcClientSecret && { oidcClientSecret: formData.oidcClientSecret })
- });
- $formInputs.oidcClientSecret.value = '';
- toast.success(m.security_settings_saved());
- } catch (error: any) {
- console.error('Failed to save settings:', error);
- toast.error(m.security_settings_save_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ await settingsForm.updateSettings({
+ authLocalEnabled: formData.authLocalEnabled,
+ authSessionTimeout: formData.authSessionTimeout,
+ authPasswordPolicy: formData.authPasswordPolicy,
+ oidcEnabled: formData.oidcEnabled,
+ oidcMergeAccounts: formData.oidcMergeAccounts,
+ oidcSkipTlsVerify: formData.oidcSkipTlsVerify,
+ oidcAutoRedirectToProvider: formData.oidcAutoRedirectToProvider,
+ oidcClientId: formData.oidcClientId,
+ oidcIssuerUrl: formData.oidcIssuerUrl,
+ oidcScopes: formData.oidcScopes,
+ oidcGroupsClaim: formData.oidcGroupsClaim,
+ oidcProviderName: formData.oidcProviderName,
+ oidcProviderLogoUrl: formData.oidcProviderLogoUrl,
+ ...(formData.oidcClientSecret && { oidcClientSecret: formData.oidcClientSecret })
+ });
+ $formInputs.oidcClientSecret.value = '';
+ toast.success(m.security_settings_saved());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Failed to save settings:', error);
+ toast.error(m.security_settings_save_failed());
+ }
} finally {
settingsForm.setLoading(false);
}
diff --git a/frontend/src/routes/(app)/settings/authentication/federated-credentials-tab.svelte b/frontend/src/routes/(app)/settings/authentication/federated-credentials-tab.svelte
index d55e977d2..fee860b6a 100644
--- a/frontend/src/routes/(app)/settings/authentication/federated-credentials-tab.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/federated-credentials-tab.svelte
@@ -1,7 +1,8 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { untrack } from 'svelte';
- import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import FederatedCredentialTable from './federated-credential-table.svelte';
import FederatedCredentialFormSheet from '#lib/components/sheets/federated-credential-form-sheet.svelte';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -67,37 +68,42 @@
const loading = isEditMode ? 'editing' : 'creating';
isLoading[loading] = true;
- try {
- const safeName = credential.name?.trim() || m.common_unknown();
- if (isEditMode && credentialId) {
- const result = await tryCatch(federatedCredentialService.update(credentialId, credential));
- handleApiResultWithCallbacks({
- result,
- message: m.federated_credential_update_failed({ name: safeName }),
- setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async () => {
- toast.success(m.federated_credential_updated_success({ name: safeName }));
- await refreshFederatedCredentials();
- isDialogOpen.edit = false;
- credentialToEdit = null;
- }
- });
- } else {
- const result = await tryCatch(federatedCredentialService.create(credential));
- handleApiResultWithCallbacks({
- result,
- message: m.federated_credential_create_failed({ name: safeName }),
- setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async (createdCredential) => {
- toast.success(m.federated_credential_created_success({ name: safeName }));
- await refreshFederatedCredentials();
- isDialogOpen.create = false;
- newlyCreatedCredential = createdCredential as FederatedCredential;
- isDialogOpen.instructions = true;
- }
- });
- }
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const safeName = credential.name?.trim() || m.common_unknown();
+ if (isEditMode && credentialId) {
+ const result = await tryCatch(federatedCredentialService.update(credentialId, credential));
+ await handleApiResultWithCallbacks({
+ result,
+ message: m.federated_credential_update_failed({ name: safeName }),
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async () => {
+ toast.success(m.federated_credential_updated_success({ name: safeName }));
+ await refreshFederatedCredentials();
+ isDialogOpen.edit = false;
+ credentialToEdit = null;
+ }
+ });
+ } else {
+ const result = await tryCatch(federatedCredentialService.create(credential));
+ await handleApiResultWithCallbacks({
+ result,
+ message: m.federated_credential_create_failed({ name: safeName }),
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async (createdCredential) => {
+ toast.success(m.federated_credential_created_success({ name: safeName }));
+ await refreshFederatedCredentials();
+ isDialogOpen.create = false;
+ newlyCreatedCredential = createdCredential as FederatedCredential;
+ isDialogOpen.instructions = true;
+ }
+ });
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Failed to submit federated credential:', error);
}
}
diff --git a/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte b/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte
index 0ccd79516..c03dcb6fc 100644
--- a/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte
@@ -6,7 +6,7 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { OidcRoleMapping, Role } from '#lib/types/auth.js';
import type { Environment } from '#lib/types/environment.js';
@@ -109,7 +109,7 @@
destructive: true,
action: async () => {
isLoading.removing = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(oidcMappingService.delete(mapping.id)),
message: m.oidc_mappings_delete_failed(),
setLoadingState: (value) => (isLoading.removing = value),
diff --git a/frontend/src/routes/(app)/settings/backups/+page.svelte b/frontend/src/routes/(app)/settings/backups/+page.svelte
index 1f90e7a2f..8bd2cb1c0 100644
--- a/frontend/src/routes/(app)/settings/backups/+page.svelte
+++ b/frontend/src/routes/(app)/settings/backups/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { goto } from '$app/navigation';
import { useBackupActivity } from '#lib/hooks/use-backup-activity.svelte.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
@@ -141,13 +143,20 @@
newRecoveryKey = '';
generatingKey = true;
try {
- const generated = await systemBackupService.generateRecoveryKey();
- await systemBackupService.setRecoveryKey(generated.recoveryKey);
- newRecoveryKey = generated.recoveryKey;
- policyCollection = { ...policyCollection, recoveryKeyStored: true };
- keyOpen = true;
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.system_backups_recovery_key_save_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const generated = await systemBackupService.generateRecoveryKey();
+ await systemBackupService.setRecoveryKey(generated.recoveryKey);
+ newRecoveryKey = generated.recoveryKey;
+ policyCollection = { ...policyCollection, recoveryKeyStored: true };
+ keyOpen = true;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.system_backups_recovery_key_save_failed());
+ }
} finally {
generatingKey = false;
}
@@ -217,19 +226,26 @@
return;
restoringFiles = true;
try {
- const result = await systemBackupService.restoreFiles(restoreFilesTarget.id, restoreFilesRecoveryKey.trim(), {
- paths: restoreFilesSelectedPaths,
- selectAll: restoreFilesSelectAll,
- search: restoreFilesSelectAll ? restoreFilesSearch.trim() : undefined
- });
- const projectQueryKey = queryKeys.projects.environment('0');
- await queryClient.cancelQueries({ queryKey: projectQueryKey });
- queryClient.removeQueries({ queryKey: projectQueryKey });
- toast.success(m.system_backups_restore_selection_success(), activityToastOptions(extractActivityId(result)));
- closeRestoreFiles();
- await refresh();
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.system_backups_restore_files_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await systemBackupService.restoreFiles(restoreFilesTarget.id, restoreFilesRecoveryKey.trim(), {
+ paths: restoreFilesSelectedPaths,
+ selectAll: restoreFilesSelectAll,
+ search: restoreFilesSelectAll ? restoreFilesSearch.trim() : undefined
+ });
+ const projectQueryKey = queryKeys.projects.environment('0');
+ await queryClient.cancelQueries({ queryKey: projectQueryKey });
+ queryClient.removeQueries({ queryKey: projectQueryKey });
+ toast.success(m.system_backups_restore_selection_success(), activityToastOptions(extractActivityId(result)));
+ closeRestoreFiles();
+ await refresh();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.system_backups_restore_files_failed());
+ }
} finally {
restoringFiles = false;
}
@@ -256,10 +272,17 @@
if (systemVolumeOptionsLoading || systemVolumeOptionsLoaded) return;
systemVolumeOptionsLoading = true;
try {
- systemVolumeOptions = await systemBackupService.listSystemVolumeOptions();
- systemVolumeOptionsLoaded = true;
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.system_volume_backups_options_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ systemVolumeOptions = await systemBackupService.listSystemVolumeOptions();
+ systemVolumeOptionsLoaded = true;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.system_volume_backups_options_failed());
+ }
} finally {
systemVolumeOptionsLoading = false;
}
@@ -276,9 +299,14 @@
async function openVolumeBackups(backup: BackupHistoryEntry) {
const localEnvironment = environmentStore.getLocalEnvironment();
if (!localEnvironment) return;
- try {
- await environmentStore.setEnvironment(localEnvironment);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await environmentStore.setEnvironment(localEnvironment);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.environments_connect_error());
return;
}
@@ -293,10 +321,15 @@
if (autoDiscovered || !policyCollection.recoveryKeyStored || data.destinations.length === 0) return;
autoDiscovered = true;
void (async () => {
- try {
- const counts = await Promise.all(data.destinations.map((item) => systemBackupService.discover(item.id, '')));
- if (counts.some((count) => count > 0)) await refresh();
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const counts = await Promise.all(data.destinations.map((item) => systemBackupService.discover(item.id, '')));
+ if (counts.some((count) => count > 0)) await refresh();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.warn('S3 backup discovery failed', error);
}
})();
@@ -315,67 +348,80 @@
if (loading || invalid || (action === 'create' && backupActivity.activeIds.length)) return;
loading = true;
try {
- if (action === 'create') {
- if (backupType === 'system') {
- const result = await systemBackupService.create(
- backupConfiguration === 'custom'
- ? { destination, s3DestinationId: destination === 'local' ? '' : s3DestinationId, recoveryKey }
- : { policyId: backupConfiguration, recoveryKey }
- );
- backupActivity.accepted(extractActivityId(result));
- toast.success(m.backups_started(), activityToastOptions(extractActivityId(result), false));
- } else {
- const result = await systemBackupService.runSystemVolumeBackups(
- backupConfiguration === 'custom'
- ? {
- custom: {
- destination,
- s3DestinationId: destination === 'local' ? '' : s3DestinationId,
- stopContainers,
- selectionMode,
- volumeNames,
- ignoreAnonymous
- }
- }
- : { policyId: backupConfiguration }
- );
- backupActivity.accepted(result.activityId);
- toast.success(m.backups_started(), activityToastOptions(result.activityId, false));
- }
- actionOpen = false;
- loading = false;
- void refresh().catch((error) => console.warn('Failed to refresh backup history', error));
- } else if (action === 'restore' && selected) {
- await systemBackupService.restore(selected.id, recoveryKey);
- toast.success(m.system_backups_restore_started());
- } else if (action === 'upload' && selected) {
- await systemBackupService.upload(selected.id, s3DestinationId, recoveryKey);
- toast.success(m.backups_upload_s3_success());
- await refresh();
- } else if (action === 'delete' && selected) {
- await systemBackupService.delete(selected.id, recoveryKey);
- toast.success(m.system_backups_deleted());
- await refresh();
- } else if (action === 'discover') {
- const count = await systemBackupService.discover(s3DestinationId, recoveryKey);
- toast.success(m.system_backups_discovered({ count }));
- await refresh();
+ const operationResult = await tryCatch(
+ (async () => {
+ if (action === 'create') {
+ if (backupType === 'system') {
+ const result = await systemBackupService.create(
+ backupConfiguration === 'custom'
+ ? { destination, s3DestinationId: destination === 'local' ? '' : s3DestinationId, recoveryKey }
+ : { policyId: backupConfiguration, recoveryKey }
+ );
+ backupActivity.accepted(extractActivityId(result));
+ toast.success(m.backups_started(), activityToastOptions(extractActivityId(result), false));
+ } else {
+ const result = await systemBackupService.runSystemVolumeBackups(
+ backupConfiguration === 'custom'
+ ? {
+ custom: {
+ destination,
+ s3DestinationId: destination === 'local' ? '' : s3DestinationId,
+ stopContainers,
+ selectionMode,
+ volumeNames,
+ ignoreAnonymous
+ }
+ }
+ : { policyId: backupConfiguration }
+ );
+ backupActivity.accepted(result.activityId);
+ toast.success(m.backups_started(), activityToastOptions(result.activityId, false));
+ }
+ actionOpen = false;
+ loading = false;
+ void tryCatch(refresh()).then((result) => {
+ if (result.error) {
+ const error: Error = result.error;
+ return console.warn('Failed to refresh backup history', error);
+ }
+ return result.data;
+ });
+ } else if (action === 'restore' && selected) {
+ await systemBackupService.restore(selected.id, recoveryKey);
+ toast.success(m.system_backups_restore_started());
+ } else if (action === 'upload' && selected) {
+ await systemBackupService.upload(selected.id, s3DestinationId, recoveryKey);
+ toast.success(m.backups_upload_s3_success());
+ await refresh();
+ } else if (action === 'delete' && selected) {
+ await systemBackupService.delete(selected.id, recoveryKey);
+ toast.success(m.system_backups_deleted());
+ await refresh();
+ } else if (action === 'discover') {
+ const count = await systemBackupService.discover(s3DestinationId, recoveryKey);
+ toast.success(m.system_backups_discovered({ count }));
+ await refresh();
+ }
+ actionOpen = false;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ const fallback =
+ action === 'restore'
+ ? m.system_backups_restore_failed()
+ : action === 'delete'
+ ? m.system_backups_delete_failed()
+ : action === 'upload'
+ ? m.backups_upload_s3_failed()
+ : action === 'discover'
+ ? m.system_backups_discover_failed()
+ : backupType === 'volume'
+ ? m.system_volume_backups_run_failed()
+ : m.system_backups_create_failed();
+ toast.error(error instanceof Error ? error.message : fallback);
}
- actionOpen = false;
- } catch (error) {
- const fallback =
- action === 'restore'
- ? m.system_backups_restore_failed()
- : action === 'delete'
- ? m.system_backups_delete_failed()
- : action === 'upload'
- ? m.backups_upload_s3_failed()
- : action === 'discover'
- ? m.system_backups_discover_failed()
- : backupType === 'volume'
- ? m.system_volume_backups_run_failed()
- : m.system_backups_create_failed();
- toast.error(error instanceof Error ? error.message : fallback);
} finally {
loading = false;
}
diff --git a/frontend/src/routes/(app)/settings/backups/s3/+page.svelte b/frontend/src/routes/(app)/settings/backups/s3/+page.svelte
index 20ea2a076..e97a5d916 100644
--- a/frontend/src/routes/(app)/settings/backups/s3/+page.svelte
+++ b/frontend/src/routes/(app)/settings/backups/s3/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { toast } from 'svelte-sonner';
import settingsStore from '#lib/stores/config-store.js';
import { SettingsPageLayout, type SettingsActionButton } from '#lib/layouts/index.js';
@@ -32,18 +34,25 @@
async function saveDestination(input: CreateS3Destination) {
saving = true;
try {
- if (selected) {
- await s3DestinationService.update(selected.id, input);
- toast.success(m.s3_destination_updated({ name: input.name }));
- } else {
- await s3DestinationService.create(input);
- toast.success(m.s3_destination_created({ name: input.name }));
+ const operationResult = await tryCatch(
+ (async () => {
+ if (selected) {
+ await s3DestinationService.update(selected.id, input);
+ toast.success(m.s3_destination_updated({ name: input.name }));
+ } else {
+ await s3DestinationService.create(input);
+ toast.success(m.s3_destination_created({ name: input.name }));
+ }
+ destinations = await s3DestinationService.list(requestOptions);
+ dialogOpen = false;
+ selected = null;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.s3_destination_save_failed());
}
- destinations = await s3DestinationService.list(requestOptions);
- dialogOpen = false;
- selected = null;
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.s3_destination_save_failed());
} finally {
saving = false;
}
@@ -57,11 +66,16 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- try {
- await s3DestinationService.delete(destination.id);
- destinations = await s3DestinationService.list(requestOptions);
- toast.success(m.s3_destination_deleted({ name: destination.name }));
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await s3DestinationService.delete(destination.id);
+ destinations = await s3DestinationService.list(requestOptions);
+ toast.success(m.s3_destination_deleted({ name: destination.name }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.s3_destination_delete_failed());
}
}
diff --git a/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte b/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte
index 3feb27822..d5d7e8f20 100644
--- a/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte
+++ b/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import FormInput from '#lib/components/form/form-input.svelte';
@@ -103,15 +105,22 @@
testedConfiguration = null;
testing = true;
try {
- if (destination) {
- await s3DestinationService.test(destination.id, data);
- } else {
- await s3DestinationService.testConfiguration(data);
+ const operationResult = await tryCatch(
+ (async () => {
+ if (destination) {
+ await s3DestinationService.test(destination.id, data);
+ } else {
+ await s3DestinationService.testConfiguration(data);
+ }
+ testedConfiguration = testedCandidate;
+ toast.success(m.s3_destination_test_success({ name: data.name }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.s3_destination_test_failed({ name: data.name }));
}
- testedConfiguration = testedCandidate;
- toast.success(m.s3_destination_test_success({ name: data.name }));
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.s3_destination_test_failed({ name: data.name }));
} finally {
testing = false;
}
diff --git a/frontend/src/routes/(app)/settings/backups/s3/s3-destination-table.svelte b/frontend/src/routes/(app)/settings/backups/s3/s3-destination-table.svelte
index 7fc69e6d0..26975d220 100644
--- a/frontend/src/routes/(app)/settings/backups/s3/s3-destination-table.svelte
+++ b/frontend/src/routes/(app)/settings/backups/s3/s3-destination-table.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import RemoveMenuItem from '#lib/components/arcane-table/cells/remove-menu-item.svelte';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
@@ -50,10 +52,17 @@
async function testDestination(destination: S3Destination) {
testingId = destination.id;
try {
- await s3DestinationService.test(destination.id);
- toast.success(m.s3_destination_test_success({ name: destination.name }));
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.s3_destination_test_failed({ name: destination.name }));
+ const operationResult = await tryCatch(
+ (async () => {
+ await s3DestinationService.test(destination.id);
+ toast.success(m.s3_destination_test_success({ name: destination.name }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.s3_destination_test_failed({ name: destination.name }));
+ }
} finally {
testingId = null;
}
diff --git a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
index 7204de40c..9d6a263d5 100644
--- a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
+++ b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { onMount } from 'svelte';
import { cn } from '#lib/utils.js';
import { m } from '#lib/paraglide/messages.js';
@@ -233,9 +235,14 @@
}
async function refresh() {
- try {
- applySnapshot(await diagnosticsService.getDiagnostics());
- } catch (e) {
+ const operationResult = await tryCatch(
+ (async () => {
+ applySnapshot(await diagnosticsService.getDiagnostics());
+ })()
+ );
+ if (operationResult.error !== null) {
+ const e = operationResult.error;
+
error = e instanceof Error ? e.message : m.diagnostics_error_load();
}
}
@@ -247,9 +254,14 @@
async function loadDump(name: 'goroutine' | 'heap') {
dumpLoading[name] = true;
try {
- dumpText[name] = await diagnosticsService.getDump(name);
- } catch (e) {
- dumpText[name] = e instanceof Error ? e.message : m.diagnostics_error_dump();
+ const operationResult = await tryCatch((async () => diagnosticsService.getDump(name))());
+ if (operationResult.error !== null) {
+ const e = operationResult.error;
+
+ dumpText[name] = e instanceof Error ? e.message : m.diagnostics_error_dump();
+ } else {
+ dumpText[name] = operationResult.data;
+ }
} finally {
dumpLoading[name] = false;
}
@@ -288,9 +300,16 @@
async function download(p: PprofProfile) {
downloading = p;
try {
- await diagnosticsService.downloadProfile(p);
- } catch (e) {
- error = e instanceof Error ? e.message : m.diagnostics_error_download();
+ const operationResult = await tryCatch(
+ (async () => {
+ await diagnosticsService.downloadProfile(p);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const e = operationResult.error;
+
+ error = e instanceof Error ? e.message : m.diagnostics_error_download();
+ }
} finally {
downloading = null;
}
diff --git a/frontend/src/routes/(app)/settings/diagnostics/diagnostic-leak-panel.svelte b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-leak-panel.svelte
index 920d99ac5..74636ffe0 100644
--- a/frontend/src/routes/(app)/settings/diagnostics/diagnostic-leak-panel.svelte
+++ b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-leak-panel.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { m } from '#lib/paraglide/messages.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { AlertTriangleIcon, DownloadIcon } from '#lib/icons/index.js';
@@ -29,11 +31,18 @@
scanning = true;
error = null;
try {
- const next = await diagnosticsService.scanGoroutineLeaks();
- report = next;
- onscanned?.(next);
- } catch (e) {
- error = e instanceof Error ? e.message : m.diagnostics_error_scan_leaks();
+ const operationResult = await tryCatch(
+ (async () => {
+ const next = await diagnosticsService.scanGoroutineLeaks();
+ report = next;
+ onscanned?.(next);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const e = operationResult.error;
+
+ error = e instanceof Error ? e.message : m.diagnostics_error_scan_leaks();
+ }
} finally {
scanning = false;
}
@@ -43,9 +52,16 @@
downloading = true;
error = null;
try {
- await diagnosticsService.downloadProfile('goroutineleak');
- } catch (e) {
- error = e instanceof Error ? e.message : m.diagnostics_error_download();
+ const operationResult = await tryCatch(
+ (async () => {
+ await diagnosticsService.downloadProfile('goroutineleak');
+ })()
+ );
+ if (operationResult.error !== null) {
+ const e = operationResult.error;
+
+ error = e instanceof Error ? e.message : m.diagnostics_error_download();
+ }
} finally {
downloading = false;
}
diff --git a/frontend/src/routes/(app)/settings/jobs/+page.ts b/frontend/src/routes/(app)/settings/jobs/+page.ts
index 636699006..4b29f95c3 100644
--- a/frontend/src/routes/(app)/settings/jobs/+page.ts
+++ b/frontend/src/routes/(app)/settings/jobs/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { redirect } from '@sveltejs/kit';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { PageLoad } from './$types';
@@ -5,6 +6,6 @@ import type { PageLoad } from './$types';
// Job schedules are configured per environment; this route exists so the
// settings landing and search can link to a stable /settings URL.
export const load: PageLoad = async () => {
- const envId = await environmentStore.getCurrentEnvironmentId().catch(() => '0');
+ const envId = await tryCatch(environmentStore.getCurrentEnvironmentId()).then((result) => (result.error ? '0' : result.data));
redirect(302, `/environments/${envId}?tab=jobs`);
};
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index cf25f4c2c..ec6f76215 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -29,7 +29,8 @@
type NotificationSettingsByProvider,
updateNotificationProviderFormState
} from '#lib/utils/notification-providers.js';
- import { extractApiErrorMessage, handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api.js';
+ import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { apnsService } from '#lib/services/apns-service.js';
import type { ApnsDevice } from '#lib/types/apns.js';
import { formatRelativeTime } from '#lib/utils/formatting.js';
@@ -116,38 +117,51 @@
isLoading = true;
try {
- const errors: string[] = [];
- for (const provider of changedProviders) {
- try {
- const settings = notificationProviderFormValuesToSettings(provider, providerValues[provider]);
- const saved = await notificationService.updateSettings(provider, settings);
- savedSettings = { ...savedSettings, [provider]: saved };
- providerBaselines = updateNotificationProviderFormState(providerBaselines, provider, providerValues[provider]);
- } catch (error) {
- errors.push(
- m.notifications_saved_failed({
- provider: getNotificationProviderDefinition(provider).label(),
- error: extractApiErrorMessage(error)
- })
- );
- }
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ const errors: string[] = [];
+ for (const provider of changedProviders) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const settings = notificationProviderFormValuesToSettings(provider, providerValues[provider]);
+ const saved = await notificationService.updateSettings(provider, settings);
+ savedSettings = { ...savedSettings, [provider]: saved };
+ providerBaselines = updateNotificationProviderFormState(providerBaselines, provider, providerValues[provider]);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ errors.push(
+ m.notifications_saved_failed({
+ provider: getNotificationProviderDefinition(provider).label(),
+ error: extractApiErrorMessage(error)
+ })
+ );
+ }
+ }
- if (errors.length === 0) {
- toast.success(m.general_settings_saved());
- } else {
- errors.forEach((err) => toast.error(err));
+ if (errors.length === 0) {
+ toast.success(m.general_settings_saved());
+ } else {
+ errors.forEach((err) => toast.error(err));
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Error saving notification settings:', error);
+ toast.error(m.settings_notifications_save_error());
}
- } catch (error) {
- console.error('Error saving notification settings:', error);
- toast.error(m.settings_notifications_save_error());
} finally {
isLoading = false;
}
}
async function handleMobilePushToggle(enabled: boolean) {
- handleApiResultWithCallbacks<Settings>({
+ savingMobilePush = true;
+ await handleApiResultWithCallbacks<Settings>({
result: await tryCatch(settingsService.updateSettings({ apnsEnabled: enabled })),
message: m.common_update_failed({ resource: m.settings() }),
setLoadingState: (value) => (savingMobilePush = value),
@@ -205,14 +219,21 @@
async function executeTest(provider: NotificationProviderKey, testType: string = 'simple') {
isTesting = true;
try {
- const result = await notificationService.testNotification(provider, testType);
- if (result?.data?.warning) {
- toast.warning(m.notifications_test_warning({ warning: result.data.warning }));
- } else {
- toast.success(m.notifications_test_success({ provider: getNotificationProviderDefinition(provider).label() }));
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await notificationService.testNotification(provider, testType);
+ if (result?.data?.warning) {
+ toast.warning(m.notifications_test_warning({ warning: result.data.warning }));
+ } else {
+ toast.success(m.notifications_test_success({ provider: getNotificationProviderDefinition(provider).label() }));
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(m.notifications_test_failed({ error: extractApiErrorMessage(error) }));
}
- } catch (error) {
- toast.error(m.notifications_test_failed({ error: extractApiErrorMessage(error) }));
} finally {
isTesting = false;
}
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.ts b/frontend/src/routes/(app)/settings/notifications/+page.ts
index 8aa0b0479..651ff7b61 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.ts
+++ b/frontend/src/routes/(app)/settings/notifications/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { notificationService } from '#lib/services/notification-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { PageLoad } from './$types';
@@ -5,17 +6,24 @@ import type { PageLoad } from './$types';
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
- try {
- const notificationSettings = await queryClient.fetchQuery({
- queryKey: queryKeys.notifications.settings(),
- queryFn: () => notificationService.getSettings()
- });
+ const operationResult = await tryCatch(
+ (async () => {
+ const notificationSettings = await queryClient.fetchQuery({
+ queryKey: queryKeys.notifications.settings(),
+ queryFn: () => notificationService.getSettings()
+ });
+
+ return {
+ notificationSettings
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
- return {
- notificationSettings
- };
- } catch (error) {
console.error('Failed to load notification settings:', error);
throw error;
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte b/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
index 3e927bbda..e6c79b823 100644
--- a/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
@@ -2,7 +2,7 @@
import { toast } from 'svelte-sonner';
import { goto } from '$app/navigation';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { UpdateRole, CreateRole } from '#lib/types/auth.js';
import { m } from '#lib/paraglide/messages.js';
import { roleService } from '#lib/services/role-service.js';
@@ -15,7 +15,7 @@
async function handleSubmit(payload: UpdateRole) {
isLoading = true;
const safeName = payload.name?.trim() || data.role.name || m.common_unknown();
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(roleService.update(data.role.id, payload)),
message: m.common_update_failed({ resource: `${m.resource_role()} "${safeName}"` }),
setLoadingState: (value) => (isLoading = value),
@@ -35,7 +35,7 @@
};
const result = await tryCatch(roleService.create(clonePayload));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.roles_clone_failed(),
setLoadingState: (value) => (isLoading = value),
diff --git a/frontend/src/routes/(app)/settings/roles/[id]/+page.ts b/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
index 09388a406..b488600ae 100644
--- a/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
+++ b/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { error, redirect } from '@sveltejs/kit';
import { roleService } from '#lib/services/role-service.js';
import { userIsGlobalAdmin } from '#lib/utils/auth.js';
@@ -14,12 +15,12 @@ export const load: PageLoad = async ({ parent, params }) => {
}
const [role, permissionsManifest] = await Promise.all([
- queryClient
- .fetchQuery({
+ tryCatch(
+ queryClient.fetchQuery({
queryKey: ['roles', 'detail', params.id],
queryFn: () => roleService.get(params.id)
})
- .catch(() => null),
+ ).then((result) => (result.error ? null : result.data)),
queryClient.fetchQuery({
queryKey: ['roles', 'permissions-manifest'],
queryFn: () => roleService.getPermissionsManifest()
diff --git a/frontend/src/routes/(app)/settings/roles/new/+page.svelte b/frontend/src/routes/(app)/settings/roles/new/+page.svelte
index 0eaca65f3..c0629a823 100644
--- a/frontend/src/routes/(app)/settings/roles/new/+page.svelte
+++ b/frontend/src/routes/(app)/settings/roles/new/+page.svelte
@@ -2,7 +2,7 @@
import { toast } from 'svelte-sonner';
import { goto } from '$app/navigation';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { CreateRole } from '#lib/types/auth.js';
import { m } from '#lib/paraglide/messages.js';
import { roleService } from '#lib/services/role-service.js';
@@ -15,7 +15,7 @@
async function handleSubmit(payload: CreateRole) {
isLoading = true;
const safeName = payload.name?.trim() || m.common_unknown();
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(roleService.create(payload)),
message: m.common_create_failed({ resource: `${m.resource_role()} "${safeName}"` }),
setLoadingState: (value) => (isLoading = value),
diff --git a/frontend/src/routes/(app)/settings/users/+page.svelte b/frontend/src/routes/(app)/settings/users/+page.svelte
index be9d7e278..46bb09879 100644
--- a/frontend/src/routes/(app)/settings/users/+page.svelte
+++ b/frontend/src/routes/(app)/settings/users/+page.svelte
@@ -2,7 +2,7 @@
import { UsersIcon } from '#lib/icons/index.js';
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import UserTable from './user-table.svelte';
import UserFormSheet from '#lib/components/sheets/user-form-sheet.svelte';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -85,76 +85,81 @@
const loading = isEditMode ? 'editing' : 'creating';
isLoading[loading] = true;
- try {
- if (isEditMode && userId) {
- const safeUsername = userToEdit?.username || m.common_unknown();
- // Split: profile fields go to PUT /users/{id}; role assignments
- // go to PUT /users/{id}/role-assignments (separate endpoint).
- const { roleAssignments, ...profile } = user;
+ const operationResult = await tryCatch(
+ (async () => {
+ if (isEditMode && userId) {
+ const safeUsername = userToEdit?.username || m.common_unknown();
+ // Split: profile fields go to PUT /users/{id}; role assignments
+ // go to PUT /users/{id}/role-assignments (separate endpoint).
+ const { roleAssignments, ...profile } = user;
- // OIDC users submit role assignments only — skip the empty profile PUT.
- if (Object.keys(profile).length === 0 && isAdmin && roleAssignments) {
- const assignmentsResult = await tryCatch(roleService.setUserAssignments(userId, { assignments: roleAssignments }));
+ // OIDC users submit role assignments only — skip the empty profile PUT.
+ if (Object.keys(profile).length === 0 && isAdmin && roleAssignments) {
+ const assignmentsResult = await tryCatch(roleService.setUserAssignments(userId, { assignments: roleAssignments }));
+ await handleApiResultWithCallbacks({
+ result: assignmentsResult,
+ message: m.common_update_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async () => {
+ await completeUserEdit(safeUsername);
+ }
+ });
+ return !assignmentsResult.error;
+ }
+
+ const result = await tryCatch(userService.update(userId, profile));
await handleApiResultWithCallbacks({
- result: assignmentsResult,
+ result,
message: m.common_update_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
setLoadingState: (value) => (isLoading[loading] = value),
onSuccess: async () => {
+ if (isAdmin && roleAssignments) {
+ await roleService.setUserAssignments(userId, { assignments: roleAssignments });
+ }
await completeUserEdit(safeUsername);
}
});
- return !assignmentsResult.error;
- }
-
- const result = await tryCatch(userService.update(userId, profile));
- await handleApiResultWithCallbacks({
- result,
- message: m.common_update_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
- setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async () => {
- if (isAdmin && roleAssignments) {
- await roleService.setUserAssignments(userId, { assignments: roleAssignments });
- }
- await completeUserEdit(safeUsername);
+ return !result.error;
+ } else {
+ if (!user.username) {
+ toast.error(m.common_username_required());
+ isLoading[loading] = false;
+ return false;
}
- });
- return !result.error;
- } else {
- if (!user.username) {
- toast.error(m.common_username_required());
- isLoading[loading] = false;
- return false;
- }
- const safeUsername = user.username!.trim() || m.common_unknown();
+ const safeUsername = user.username!.trim() || m.common_unknown();
- const createUser: CreateUser = {
- username: user.username!,
- displayName: user.displayName,
- email: user.email,
- password: user.password!
- };
+ const createUser: CreateUser = {
+ username: user.username!,
+ displayName: user.displayName,
+ email: user.email,
+ password: user.password!
+ };
- const result = await tryCatch(userService.create(createUser));
- await handleApiResultWithCallbacks({
- result,
- message: m.common_create_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
- setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async (created) => {
- if (isAdmin && user.roleAssignments && created?.id) {
- await roleService.setUserAssignments(created.id, { assignments: user.roleAssignments });
+ const result = await tryCatch(userService.create(createUser));
+ await handleApiResultWithCallbacks({
+ result,
+ message: m.common_create_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async (created) => {
+ if (isAdmin && user.roleAssignments && created?.id) {
+ await roleService.setUserAssignments(created.id, { assignments: user.roleAssignments });
+ }
+ toast.success(m.common_create_success({ resource: `${m.resource_user()} "${safeUsername}"` }));
+ users = await userService.getUsers(requestOptions);
+ isDialogOpen.create = false;
}
- toast.success(m.common_create_success({ resource: `${m.resource_user()} "${safeUsername}"` }));
- users = await userService.getUsers(requestOptions);
- isDialogOpen.create = false;
- }
- });
- return !result.error;
- }
- } catch (error) {
+ });
+ return !result.error;
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
console.error('Failed to submit user:', error);
return false;
}
+ return operationResult.data;
}
// Avatar policy: server-wide settings that belong with user management.
@@ -171,11 +176,16 @@
});
async function saveAvatarSettings(patch: Partial<Settings>) {
- try {
- const updated = await settingsService.updateSettings(patch);
- settingsStore.set(updated);
- toast.success(m.common_update_success({ resource: m.settings() }));
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const updated = await settingsService.updateSettings(patch);
+ settingsStore.set(updated);
+ toast.success(m.common_update_success({ resource: m.settings() }));
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.settings() }));
}
}
diff --git a/frontend/src/routes/(app)/settings/webhooks/+page.svelte b/frontend/src/routes/(app)/settings/webhooks/+page.svelte
index ab67198f2..ed00f6d0f 100644
--- a/frontend/src/routes/(app)/settings/webhooks/+page.svelte
+++ b/frontend/src/routes/(app)/settings/webhooks/+page.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import WebhookTable from './webhook-table.svelte';
import WebhookFormSheet from '#lib/components/sheets/webhook-form-sheet.svelte';
import type { Webhook, WebhookCreated, CreateWebhook } from '#lib/types/environment.js';
@@ -38,7 +38,7 @@
async function handleCreateWebhook(webhook: CreateWebhook) {
isLoading.creating = true;
const result = await tryCatch(webhookService.create(webhook));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.webhook_create_failed({ name: webhook.name }),
setLoadingState: (value) => (isLoading.creating = value),
diff --git a/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte b/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte
index fbc4f992a..f379705c8 100644
--- a/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte
+++ b/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte
@@ -9,7 +9,7 @@
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import type { Webhook } from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { webhookService } from '#lib/services/webhook-service.js';
@@ -105,7 +105,7 @@
const name = webhook.name;
const enabling = !webhook.enabled;
isLoading.toggling = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(webhookService.update(webhook.id, { enabled: enabling })),
message: enabling ? m.webhook_enable_failed({ name }) : m.webhook_disable_failed({ name }),
setLoadingState: (value) => (isLoading.toggling = value),
@@ -125,7 +125,7 @@
destructive: true,
action: async () => {
isLoading.removing = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(webhookService.delete(webhookId)),
message: m.webhook_delete_failed({ name }),
setLoadingState: (value) => (isLoading.removing = value),
diff --git a/frontend/src/routes/(app)/swarm/cluster/+page.svelte b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
index bb400d0e5..74e9f5419 100644
--- a/frontend/src/routes/(app)/swarm/cluster/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
@@ -22,7 +22,7 @@
SwarmUpdateRequest
} from '#lib/types/swarm.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
import EasyJoinDialog from './easy-join-dialog.svelte';
@@ -139,7 +139,8 @@
request.autoLockManagers = initForm.autoLockManagers;
request.forceNewCluster = initForm.forceNewCluster;
- handleApiResultWithCallbacks({
+ isLoading.init = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.initSwarm(request)),
message: m.swarm_cluster_init_failed(),
setLoadingState: (value) => (isLoading.init = value),
@@ -164,7 +165,8 @@
if (joinForm.listenAddr.trim()) request.listenAddr = joinForm.listenAddr.trim();
if (joinForm.advertiseAddr.trim()) request.advertiseAddr = joinForm.advertiseAddr.trim();
- handleApiResultWithCallbacks({
+ isLoading.join = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.joinSwarm(request)),
message: m.swarm_cluster_join_failed(),
setLoadingState: (value) => (isLoading.join = value),
@@ -176,7 +178,8 @@
}
async function handleLeave() {
- handleApiResultWithCallbacks({
+ isLoading.leave = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.leaveSwarm({ force: leaveForce })),
message: m.swarm_cluster_leave_failed(),
setLoadingState: (value) => (isLoading.leave = value),
@@ -194,7 +197,8 @@
return;
}
- handleApiResultWithCallbacks({
+ isLoading.unlock = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.unlockSwarm({ key: unlockInput.trim() })),
message: m.swarm_cluster_unlock_failed(),
setLoadingState: (value) => (isLoading.unlock = value),
@@ -208,7 +212,8 @@
}
async function handleRotateTokens() {
- handleApiResultWithCallbacks({
+ isLoading.rotateTokens = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(
swarmService.rotateSwarmJoinTokens({
rotateManagerToken: true,
@@ -240,7 +245,8 @@
request.version = parsedVersion;
}
- handleApiResultWithCallbacks({
+ isLoading.updateSpec = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.updateSwarmSpec(request)),
message: m.swarm_cluster_update_spec_failed(),
setLoadingState: (value) => (isLoading.updateSpec = value),
diff --git a/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte b/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte
index 6f686ff74..8978d121d 100644
--- a/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte
+++ b/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import * as Alert from '#lib/components/ui/alert/index.js';
import { Input } from '#lib/components/ui/input/index.js';
@@ -41,13 +43,20 @@
targets = {};
results = [];
try {
- const candidateData = await swarmService.getSwarmJoinCandidates(managerEnvironmentId);
- candidates = targetEnvironmentId
- ? candidateData.filter((candidate) => candidate.environmentId === targetEnvironmentId)
- : candidateData;
- if (targetEnvironmentId && candidates[0]) toggleCandidate(candidates[0], true);
- } catch (error) {
- errorMessage = extractApiErrorMessage(error);
+ const operationResult = await tryCatch(
+ (async () => {
+ const candidateData = await swarmService.getSwarmJoinCandidates(managerEnvironmentId);
+ candidates = targetEnvironmentId
+ ? candidateData.filter((candidate) => candidate.environmentId === targetEnvironmentId)
+ : candidateData;
+ if (targetEnvironmentId && candidates[0]) toggleCandidate(candidates[0], true);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ errorMessage = extractApiErrorMessage(error);
+ }
} finally {
isLoading = false;
}
@@ -86,11 +95,21 @@
errorMessage = '';
results = [];
try {
- const response = await swarmService.joinEnvironments({ remoteAddrs: [], targets: selectedTargets }, managerEnvironmentId);
- results = response.results;
- await onComplete?.();
- } catch (error) {
- errorMessage = extractApiErrorMessage(error);
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await swarmService.joinEnvironments(
+ { remoteAddrs: [], targets: selectedTargets },
+ managerEnvironmentId
+ );
+ results = response.results;
+ await onComplete?.();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ errorMessage = extractApiErrorMessage(error);
+ }
} finally {
isLoading = false;
}
diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.svelte b/frontend/src/routes/(app)/swarm/nodes/+page.svelte
index 80eb23c2a..7df47bbdb 100644
--- a/frontend/src/routes/(app)/swarm/nodes/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Alert from '#lib/components/ui/alert/index.js';
import { AlertTriangleIcon, UsersIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -35,10 +37,7 @@
const environmentId = currentEnvironmentId;
if (!environmentId || !canManageNodes || reconciledEnvironmentId === environmentId) return;
reconciledEnvironmentId = environmentId;
- void swarmService
- .reconcileNodeAgents()
- .then(refresh)
- .catch(() => undefined);
+ void tryCatch(swarmService.reconcileNodeAgents().then(refresh)).then((result) => (result.error ? undefined : result.data));
});
const totalNodes = $derived(nodes?.pagination?.totalItems ?? nodes?.data?.length ?? 0);
diff --git a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
index 3db710932..e83024d89 100644
--- a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
@@ -22,7 +22,7 @@
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { goto } from '$app/navigation';
import { hasPermission } from '#lib/utils/auth.js';
@@ -78,12 +78,19 @@
agentDeploymentError = '';
try {
- agentDeployment = await swarmService.getNodeAgentDeployment(node.id, rotate);
- await refreshNodes();
- } catch (error) {
- agentDeployment = null;
- agentDeploymentError = extractApiErrorMessage(error);
- throw error;
+ const operationResult = await tryCatch(
+ (async () => {
+ agentDeployment = await swarmService.getNodeAgentDeployment(node.id, rotate);
+ await refreshNodes();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ agentDeployment = null;
+ agentDeploymentError = extractApiErrorMessage(error);
+ throw error;
+ }
} finally {
isAgentDeploymentLoading = false;
}
@@ -98,7 +105,7 @@
function provisionNodeEnvironment() {
if (!selectedNode) return;
- void loadAgentDeployment(selectedNode).catch(() => undefined);
+ void tryCatch(loadAgentDeployment(selectedNode)).then((result) => (result.error ? undefined : result.data));
}
async function attachEnvironment(environmentId: string) {
@@ -108,11 +115,18 @@
const attach = async () => {
isAgentDeploymentLoading = true;
try {
- await swarmService.bindNodeAgent(node.id, { environmentId, rebind: true, replaceDeployment });
- toast.success(m.swarm_node_agent_attach_success());
- await refreshNodes();
- } catch (error) {
- agentDeploymentError = extractApiErrorMessage(error);
+ const operationResult = await tryCatch(
+ (async () => {
+ await swarmService.bindNodeAgent(node.id, { environmentId, rebind: true, replaceDeployment });
+ toast.success(m.swarm_node_agent_attach_success());
+ await refreshNodes();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ agentDeploymentError = extractApiErrorMessage(error);
+ }
} finally {
isAgentDeploymentLoading = false;
}
@@ -166,7 +180,7 @@
function refreshAgentDeployment() {
if (!selectedNode) return;
- void loadAgentDeployment(selectedNode).catch(() => undefined);
+ void tryCatch(loadAgentDeployment(selectedNode)).then((result) => (result.error ? undefined : result.data));
}
function regenerateAgentDeployment() {
@@ -180,10 +194,13 @@
label: m.environments_regenerate_api_key(),
destructive: true,
action: async () => {
- try {
- await loadAgentDeployment(node, true);
- toast.success(m.environments_regenerate_key_success());
- } catch {
+ const operationResult = await tryCatch(
+ (async () => {
+ await loadAgentDeployment(node, true);
+ toast.success(m.environments_regenerate_key_success());
+ })()
+ );
+ if (operationResult.error !== null) {
toast.error(m.environments_regenerate_key_failed());
}
}
@@ -196,6 +213,7 @@
}
async function mutateNode(action: () => Promise<void>, successMessage: string, failureMessage: string) {
+ isLoading = true;
await handleApiResultWithCallbacks({
result: await tryCatch(action()),
message: failureMessage,
diff --git a/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.svelte b/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.svelte
index 1505c25b3..4a69a30b9 100644
--- a/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import { Input } from '#lib/components/ui/input/index.js';
@@ -25,10 +27,17 @@
if (!key.trim() || isReservedPrefix) return;
isSubmitting = true;
try {
- await onAdd(key.trim(), value.trim());
- handleCancel();
- } catch (err) {
- toast.error(m.common_update_failed({ resource: m.common_labels() }) + ': ' + extractApiErrorMessage(err));
+ const operationResult = await tryCatch(
+ (async () => {
+ await onAdd(key.trim(), value.trim());
+ handleCancel();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ toast.error(m.common_update_failed({ resource: m.common_labels() }) + ': ' + extractApiErrorMessage(err));
+ }
} finally {
isSubmitting = false;
}
diff --git a/frontend/src/routes/(app)/swarm/services/+page.svelte b/frontend/src/routes/(app)/swarm/services/+page.svelte
index e82b0df26..a5be7e13b 100644
--- a/frontend/src/routes/(app)/swarm/services/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/services/+page.svelte
@@ -3,7 +3,7 @@
import { m } from '#lib/paraglide/messages.js';
import { swarmService } from '#lib/services/swarm-service.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { ResourcePageLayout, type StatCardConfig } from '#lib/layouts/index.js';
import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
@@ -40,7 +40,8 @@
async function handleCreateService(payload: { spec: Record<string, unknown>; options?: Record<string, unknown> }) {
const spec = payload.spec as unknown as SwarmServiceCreateSpec;
- handleApiResultWithCallbacks({
+ isLoading.creating = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.createService({ spec })),
message: m.common_create_failed({ resource: `${m.swarm_service()} "${spec.Name}"` }),
setLoadingState: (v) => (isLoading.creating = v),
diff --git a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte
index a7dfce1ee..613bc180c 100644
--- a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte
@@ -8,7 +8,7 @@
import * as Tabs from '#lib/components/ui/tabs/index.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { swarmService } from '#lib/services/swarm-service.js';
import type {
@@ -215,7 +215,7 @@
async function handleUpdate(payload: { spec: Record<string, unknown>; options?: Record<string, unknown> }) {
if (!service?.id) return;
isLoading.update = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.updateService(service.id, { version: editVersion, ...payload })),
message: m.common_update_failed({ resource: `${m.swarm_service()} "${serviceName}"` }),
setLoadingState: (v) => (isLoading.update = v),
@@ -236,7 +236,7 @@
destructive: false,
action: async () => {
isLoading.rollback = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.rollbackService(service.id)),
message: m.swarm_service_rollback_failed({ name: serviceName }),
setLoadingState: (v) => (isLoading.rollback = v),
@@ -259,7 +259,7 @@
destructive: true,
action: async () => {
isLoading.remove = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.removeService(service.id)),
message: m.common_delete_failed({ resource: `${m.swarm_service()} "${serviceName}"` }),
setLoadingState: (v) => (isLoading.remove = v),
@@ -277,7 +277,7 @@
if (!service?.id || !canScaleService) return;
const replicas = Math.max(0, Number(scaleReplicas) || 0);
isLoading.scale = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.scaleService(service.id, { replicas })),
message: m.common_update_failed({ resource: `${m.swarm_service()} "${serviceName}"` }),
setLoadingState: (v) => (isLoading.scale = v),
diff --git a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.ts b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.ts
index bd887c6e4..0432c25f6 100644
--- a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.ts
+++ b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import { swarmService } from '#lib/services/swarm-service.js';
@@ -5,19 +6,26 @@ import { swarmService } from '#lib/services/swarm-service.js';
export const load: PageLoad = async ({ params }) => {
const serviceId = params.serviceId;
- try {
- const service = await swarmService.getService(serviceId);
+ const operationResult = await tryCatch(
+ (async () => {
+ const service = await swarmService.getService(serviceId);
- if (!service) {
- throw error(404, 'Service not found');
- }
+ if (!service) {
+ throw error(404, 'Service not found');
+ }
+
+ return { service };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- return { service };
- } catch (err: any) {
console.error('Failed to load service:', err);
- if (err.status === 404) {
+ if ('status' in err && err.status === 404) {
throw err;
}
throw error(500, err.message || 'Failed to load service details');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
index 3d75b950a..e346d5000 100644
--- a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import * as Card from '#lib/components/ui/card/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -23,12 +25,19 @@
async function loadTasks() {
isLoading = true;
try {
- const result = await swarmService.getServiceTasks(serviceId, {
- pagination: { page: 1, limit: 100 }
- });
- tasks = sortSwarmTasks(result.data ?? []);
- } catch (err) {
- console.error(m.swarm_service_tasks_load_failed_log(), err);
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await swarmService.getServiceTasks(serviceId, {
+ pagination: { page: 1, limit: 100 }
+ });
+ tasks = sortSwarmTasks(result.data ?? []);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ console.error(m.swarm_service_tasks_load_failed_log(), err);
+ }
} finally {
isLoading = false;
hasLoaded = true;
diff --git a/frontend/src/routes/(app)/swarm/services/services-table.svelte b/frontend/src/routes/(app)/swarm/services/services-table.svelte
index eb3010f77..b4c7745de 100644
--- a/frontend/src/routes/(app)/swarm/services/services-table.svelte
+++ b/frontend/src/routes/(app)/swarm/services/services-table.svelte
@@ -12,7 +12,7 @@
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { goto } from '$app/navigation';
import { getSwarmServiceModeLabel, getSwarmServiceModeVariant } from '#lib/utils/docker.js';
@@ -76,7 +76,8 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isLoading.remove = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.removeService(service.id)),
message: m.common_delete_failed({ resource: `${m.swarm_service()} "${service.name}"` }),
setLoadingState: (v) => (isLoading.remove = v),
diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
index 64d6000cd..a8efeb2cf 100644
--- a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
@@ -13,7 +13,7 @@
import { m } from '#lib/paraglide/messages.js';
import { swarmService } from '#lib/services/swarm-service.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
@@ -110,16 +110,21 @@
sourceState = 'forbidden';
return;
}
- try {
- source = await swarmService.getStackSource(stackName);
- sourceState = 'available';
- } catch (err: any) {
- if (err?.status === 404) {
+ const operationResult = await tryCatch(
+ (async () => {
+ source = await swarmService.getStackSource(stackName);
+ sourceState = 'available';
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
+ if ('status' in err && err.status === 404) {
source = null;
sourceState = 'missing';
return;
}
- if (err?.status === 403) {
+ if ('status' in err && err.status === 403) {
source = null;
sourceState = 'forbidden';
return;
@@ -183,7 +188,8 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isLoading.remove = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.removeStack(stackName)),
message: m.common_delete_failed({ resource: `${m.swarm_stack()} "${stackName}"` }),
setLoadingState: (v) => (isLoading.remove = v),
diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.ts b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.ts
index 336341275..5659d8b25 100644
--- a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.ts
+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { error } from '@sveltejs/kit';
import { swarmService } from '#lib/services/swarm-service.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -29,28 +30,35 @@ export const load: PageLoad = async ({ params }) => {
}
} satisfies SearchPaginationSortRequest);
- try {
- const [stack, services, tasks] = await Promise.all([
- swarmService.getStack(stackName),
- swarmService.getStackServices(stackName, servicesRequestOptions),
- swarmService.getStackTasks(stackName, tasksRequestOptions)
- ]);
+ const operationResult = await tryCatch(
+ (async () => {
+ const [stack, services, tasks] = await Promise.all([
+ swarmService.getStack(stackName),
+ swarmService.getStackServices(stackName, servicesRequestOptions),
+ swarmService.getStackTasks(stackName, tasksRequestOptions)
+ ]);
+
+ return {
+ stack,
+ stackName,
+ services,
+ tasks,
+ source: null,
+ sourceState: 'loading' as StackSourceState,
+ servicesRequestOptions,
+ tasksRequestOptions
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- return {
- stack,
- stackName,
- services,
- tasks,
- source: null,
- sourceState: 'loading' as StackSourceState,
- servicesRequestOptions,
- tasksRequestOptions
- };
- } catch (err: any) {
console.error('Failed to load stack details:', err);
- if (err.status === 404) {
+ if ('status' in err && err.status === 404) {
throw err;
}
throw error(500, err.message || 'Failed to load stack details');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.ts b/frontend/src/routes/(app)/swarm/stacks/new/+page.ts
index 10520468d..eb5ff56a0 100644
--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.ts
+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { error } from '@sveltejs/kit';
import { templateService } from '#lib/services/template-service.js';
import { variableService } from '#lib/services/variable-service.js';
@@ -11,34 +12,59 @@ export const load: PageLoad = async ({ url }) => {
const isEditMode = sourceStackName !== null;
const sourceStackPromise = sourceStackName
- ? swarmService.getStackSource(sourceStackName).catch((err: any) => {
- console.warn('Failed to load source stack content:', err);
- if (err?.status === 404) {
- throw error(404, 'Saved source not found');
+ ? tryCatch(swarmService.getStackSource(sourceStackName)).then((result) => {
+ if (result.error) {
+ const err: any = result.error;
+
+ console.warn('Failed to load source stack content:', err);
+ if (err?.status === 404) {
+ throw error(404, 'Saved source not found');
+ }
+ throw error(err?.status || 500, err?.message || 'Failed to load saved stack source');
}
- throw error(err?.status || 500, err?.message || 'Failed to load saved stack source');
+ return result.data;
})
: Promise.resolve(null);
const [allTemplates, defaultTemplates, selectedTemplate, sourceStack, globalVariables] = await Promise.all([
- templateService.getAllTemplates().catch((err) => {
- console.warn('Failed to load templates:', err);
- return [];
+ tryCatch(templateService.getAllTemplates()).then((result) => {
+ if (result.error) {
+ const err: Error = result.error;
+
+ console.warn('Failed to load templates:', err);
+ return [];
+ }
+ return result.data;
}),
- templateService.getDefaultTemplates().catch((err) => {
- console.warn('Failed to load default templates:', err);
- return { composeTemplate: '', swarmStackTemplate: '', swarmStackEnvTemplate: '', envTemplate: '' };
+ tryCatch(templateService.getDefaultTemplates()).then((result) => {
+ if (result.error) {
+ const err: Error = result.error;
+
+ console.warn('Failed to load default templates:', err);
+ return { composeTemplate: '', swarmStackTemplate: '', swarmStackEnvTemplate: '', envTemplate: '' };
+ }
+ return result.data;
}),
templateId
- ? templateService.getTemplateContent(templateId).catch((err) => {
- console.warn('Failed to load selected template:', err);
- return null;
+ ? tryCatch(templateService.getTemplateContent(templateId)).then((result) => {
+ if (result.error) {
+ const err: Error = result.error;
+
+ console.warn('Failed to load selected template:', err);
+ return null;
+ }
+ return result.data;
})
: Promise.resolve(null),
sourceStackPromise,
- variableService.list().catch((err) => {
- console.warn('Failed to load global variables:', err);
- return [];
+ tryCatch(variableService.list()).then((result) => {
+ if (result.error) {
+ const err: Error = result.error;
+
+ console.warn('Failed to load global variables:', err);
+ return [];
+ }
+ return result.data;
})
]);
diff --git a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
index 43c220d6d..85237ab27 100644
--- a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
@@ -12,7 +12,7 @@
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { goto } from '$app/navigation';
import IfPermitted from '#lib/components/if-permitted.svelte';
@@ -39,7 +39,8 @@
label: m.common_delete(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isLoading = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(swarmService.removeStack(stack.name)),
message: m.common_delete_failed({ resource: `${m.swarm_stack()} "${stack.name}"` }),
setLoadingState: (v) => (isLoading = v),
diff --git a/frontend/src/routes/(app)/updates/+page.ts b/frontend/src/routes/(app)/updates/+page.ts
index 65a983276..f12c697eb 100644
--- a/frontend/src/routes/(app)/updates/+page.ts
+++ b/frontend/src/routes/(app)/updates/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { containerService, type ContainerListRequestOptions } from '#lib/services/container-service.js';
import { projectService } from '#lib/services/project-service.js';
import { settingsService } from '#lib/services/settings-service.js';
@@ -30,24 +31,30 @@ export const load: PageLoad = async ({ parent }) => {
let containers;
let projects;
let settings;
- try {
- [containers, projects, settings] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.containers.list(envId, containerRequestOptions),
- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.projects.list(envId, projectRequestOptions),
- queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
- }),
- // `autoUpdateExcludedContainers` drives the ignored state on container rows.
- queryClient.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- })
- ]);
- } catch (err) {
+ const operationResult = await tryCatch(
+ (async () =>
+ Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.containers.list(envId, containerRequestOptions),
+ queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.projects.list(envId, projectRequestOptions),
+ queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
+ }),
+ // `autoUpdateExcludedContainers` drives the ignored state on container rows.
+ queryClient.fetchQuery({
+ queryKey: queryKeys.settings.byEnvironment(envId),
+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
+ })
+ ]))()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
+
throwPageLoadError(err, 'Failed to load updates');
+ } else {
+ [containers, projects, settings] = operationResult.data;
}
return {
diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelte
index be0fcf834..b9d76ade8 100644
--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
@@ -128,12 +130,19 @@
const enable = item.ignored;
ignoringContainerIds = { ...ignoringContainerIds, [item.containerId]: true };
try {
- await containerService.setAutoUpdate(item.containerId, enable);
- toast.success(enable ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
- await onIgnoreChanged?.();
- } catch (error) {
- console.error('Auto-update toggle failed:', error);
- toast.error(m.auto_update_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ await containerService.setAutoUpdate(item.containerId, enable);
+ toast.success(enable ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
+ await onIgnoreChanged?.();
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ console.error('Auto-update toggle failed:', error);
+ toast.error(m.auto_update_failed());
+ }
} finally {
ignoringContainerIds = { ...ignoringContainerIds, [item.containerId]: false };
}
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
index 356b54d8f..f1e7f2bc0 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
@@ -19,7 +19,7 @@
import { formatDateTimeShort, truncateString } from '#lib/utils/formatting.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog//index.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -298,22 +298,28 @@
workspaceFileLoadErrors = removeWorkspaceFileRecord(workspaceFileLoadErrors, relativePath);
const loadVersion = workspaceFileLoadVersions.get(relativePath) ?? 0;
try {
- const file = await volumeWorkspaceService.getWorkspaceFile(volume.name, relativePath, currentEnvId);
- if (loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)) return;
- workspaceFileMetadata = { ...workspaceFileMetadata, [relativePath]: file };
- if (file.editable) {
- const content = file.content ?? '';
- loadedWorkspaceFileContents = { ...loadedWorkspaceFileContents, [relativePath]: content };
- if (workspaceFileContents[relativePath] === undefined) {
- workspaceFileContents = { ...workspaceFileContents, [relativePath]: content };
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ const file = await volumeWorkspaceService.getWorkspaceFile(volume.name, relativePath, currentEnvId);
+ if (loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)) return;
+ workspaceFileMetadata = { ...workspaceFileMetadata, [relativePath]: file };
+ if (file.editable) {
+ const content = file.content ?? '';
+ loadedWorkspaceFileContents = { ...loadedWorkspaceFileContents, [relativePath]: content };
+ if (workspaceFileContents[relativePath] === undefined) {
+ workspaceFileContents = { ...workspaceFileContents, [relativePath]: content };
+ }
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ if (loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)) return;
+ workspaceFileLoadErrors = {
+ ...workspaceFileLoadErrors,
+ [relativePath]: error instanceof Error ? error.message : String(error)
+ };
}
- } catch (error) {
- if (loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)) return;
- workspaceFileLoadErrors = {
- ...workspaceFileLoadErrors,
- [relativePath]: error instanceof Error ? error.message : String(error)
- };
} finally {
if (loadVersion === (workspaceFileLoadVersions.get(relativePath) ?? 0)) {
workspaceFileLoading = removeWorkspaceFileRecord(workspaceFileLoading, relativePath);
@@ -542,7 +548,8 @@
workspaceStagedFiles,
workspaceStagedUploadedText
);
- handleApiResultWithCallbacks({
+ isLoading.save = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(
volumeWorkspaceService.updateWorkspace(
volume.name,
@@ -573,11 +580,18 @@
showWorkspaceRestore = true;
loadingWorkspaceBackups = true;
try {
- const response = await volumeBackupService.listBackups(volume.name, { pagination: { page: 1, limit: 100 } });
- workspaceBackups = response.data;
- selectedWorkspaceBackupId = response.data[0]?.id ?? '';
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.common_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const response = await volumeBackupService.listBackups(volume.name, { pagination: { page: 1, limit: 100 } });
+ workspaceBackups = response.data;
+ selectedWorkspaceBackupId = response.data[0]?.id ?? '';
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_failed());
+ }
} finally {
loadingWorkspaceBackups = false;
}
@@ -590,10 +604,15 @@
checkingWorkspaceBackup = true;
workspaceBackupHasPath = null;
try {
- workspaceBackupHasPath = await volumeBackupService.backupHasPath(backupId, `/${relativePath}`);
- } catch (error) {
- workspaceBackupHasPath = null;
- toast.error(error instanceof Error ? error.message : m.common_failed());
+ const operationResult = await tryCatch((async () => volumeBackupService.backupHasPath(backupId, `/${relativePath}`))());
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ workspaceBackupHasPath = null;
+ toast.error(error instanceof Error ? error.message : m.common_failed());
+ } else {
+ workspaceBackupHasPath = operationResult.data;
+ }
} finally {
checkingWorkspaceBackup = false;
}
@@ -626,9 +645,14 @@
}
async function downloadVolumeWorkspaceFile(relativePath: string) {
- try {
- await volumeWorkspaceService.downloadWorkspaceFile(volume.name, relativePath, currentEnvId);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await volumeWorkspaceService.downloadWorkspaceFile(volume.name, relativePath, currentEnvId);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.common_download_error());
}
}
@@ -647,7 +671,8 @@
label: m.common_remove(),
destructive: true,
action: async () => {
- handleApiResultWithCallbacks({
+ isLoading.remove = true;
+ await handleApiResultWithCallbacks({
result: await tryCatch(volumeService.deleteVolume(safeName)),
message: m.volumes_remove_failed({ name: safeName }),
setLoadingState: (value) => (isLoading.remove = value),
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts b/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
index f167caef6..4aac847e0 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import { volumeService } from '#lib/services/volume-service.js';
@@ -11,38 +12,50 @@ export const load: PageLoad = async ({ params, parent }) => {
const { volumeName } = params;
- try {
- const volume = await queryClient.fetchQuery({
- queryKey: queryKeys.volumes.detail(envId, volumeName),
- queryFn: () => volumeService.getVolumeForEnvironment(envId, volumeName)
- });
+ const operationResult = await tryCatch(
+ (async () => {
+ const volume = await queryClient.fetchQuery({
+ queryKey: queryKeys.volumes.detail(envId, volumeName),
+ queryFn: () => volumeService.getVolumeForEnvironment(envId, volumeName)
+ });
- let containersDetailed: { id: string; name: string }[] = [];
- if (volume.containers && volume.containers.length > 0) {
- containersDetailed = await Promise.all(
- volume.containers.map(async (id: string) => {
- try {
- const c = await queryClient.fetchQuery({
- queryKey: queryKeys.containers.detail(envId, id),
- queryFn: () => containerService.getContainerForEnvironment(envId, id)
- });
- const idVal = c?.id || id;
- const nameVal = c?.name || idVal.substring(0, 12);
- return { id: idVal, name: nameVal };
- } catch {
- return { id, name: id.substring(0, 12) };
- }
- })
- );
- }
+ let containersDetailed: { id: string; name: string }[] = [];
+ if (volume.containers && volume.containers.length > 0) {
+ containersDetailed = await Promise.all(
+ volume.containers.map(async (id: string) => {
+ const operationResult = await tryCatch(
+ (async () => {
+ const c = await queryClient.fetchQuery({
+ queryKey: queryKeys.containers.detail(envId, id),
+ queryFn: () => containerService.getContainerForEnvironment(envId, id)
+ });
+ const idVal = c?.id || id;
+ const nameVal = c?.name || idVal.substring(0, 12);
+ return { id: idVal, name: nameVal };
+ })()
+ );
+ if (operationResult.error !== null) {
+ return { id, name: id.substring(0, 12) };
+ } else {
+ return operationResult.data;
+ }
+ })
+ );
+ }
+
+ return {
+ volume,
+ containersDetailed
+ };
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- return {
- volume,
- containersDetailed
- };
- } catch (err: any) {
console.error('Failed to load volume:', err);
- if (err.status === 404) throw err;
+ if ('status' in err && err.status === 404) throw err;
throw error(500, err.message || 'Failed to load volume details');
+ } else {
+ return operationResult.data;
}
};
diff --git a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
index 157eae67b..2b6fd4bbb 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { backupRunColumns, backupRunMobileFields } from '#lib/components/arcane-table/backup-columns.js';
import { m } from '#lib/paraglide/messages.js';
import { volumeBackupService, type VolumeBackupListResponse } from '#lib/services/volume-backup-service.js';
@@ -116,14 +118,21 @@
let selectedPaths = $state<string[]>([]);
let selectAllBackupFiles = $state(false);
async function loadData(options: SearchPaginationSortRequest): Promise<VolumeBackupListResponse> {
- try {
- const result = await volumeBackupService.listBackups(volumeName, options);
- backupsPaginated = result;
- backupWarnings = result.warnings ?? [];
- return result;
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await volumeBackupService.listBackups(volumeName, options);
+ backupsPaginated = result;
+ backupWarnings = result.warnings ?? [];
+ return result;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.volumes_backup_load_failed());
return backupsPaginated;
+ } else {
+ return operationResult.data;
}
}
@@ -169,17 +178,29 @@
if (creating || backupActivity.activeIds.length) return false;
creating = true;
try {
- const result = await volumeBackupService.createBackup(volumeName, request);
- showS3DestinationDialog = false;
- onDemandS3DestinationId = '';
- creating = false;
- backupActivity.accepted(canReadActivities ? extractActivityId(result) : result.id);
- toast.success(m.backups_started(), canReadActivities ? activityToastOptions(extractActivityId(result), false) : undefined);
- void loadData(requestOptions);
- return true;
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.common_failed());
- return false;
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await volumeBackupService.createBackup(volumeName, request);
+ showS3DestinationDialog = false;
+ onDemandS3DestinationId = '';
+ creating = false;
+ backupActivity.accepted(canReadActivities ? extractActivityId(result) : result.id);
+ toast.success(
+ m.backups_started(),
+ canReadActivities ? activityToastOptions(extractActivityId(result), false) : undefined
+ );
+ void loadData(requestOptions);
+ return true;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_failed());
+ return false;
+ } else {
+ return operationResult.data;
+ }
} finally {
creating = false;
}
@@ -211,14 +232,19 @@
label: m.common_remove(),
destructive: true,
action: async () => {
- try {
- const result = await volumeBackupService.deleteBackup(backup.id);
- toast.success(
- m.common_delete_success({ resource: m.volumes_workspace_backup() }),
- activityToastOptions(extractActivityId(result))
- );
- await loadData(requestOptions);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await volumeBackupService.deleteBackup(backup.id);
+ toast.success(
+ m.common_delete_success({ resource: m.volumes_workspace_backup() }),
+ activityToastOptions(extractActivityId(result))
+ );
+ await loadData(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(extractApiErrorMessage(error));
await loadData(requestOptions);
}
@@ -251,11 +277,18 @@
async function handleUpload(backup: BackupEntry, s3DestinationId: string) {
uploadingBackupId = backup.id;
try {
- const result = await volumeBackupService.uploadBackup(backup.id, s3DestinationId);
- toast.success(m.backups_upload_s3_success(), activityToastOptions(extractActivityId(result)));
- await loadData(requestOptions);
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.backups_upload_s3_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await volumeBackupService.uploadBackup(backup.id, s3DestinationId);
+ toast.success(m.backups_upload_s3_success(), activityToastOptions(extractActivityId(result)));
+ await loadData(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.backups_upload_s3_failed());
+ }
} finally {
uploadingBackupId = null;
}
@@ -273,12 +306,15 @@
async function handleRestore(backup: BackupEntry) {
// Check if volume is in use
let usageWarning = '';
- try {
- const usage = await volumeService.getVolumeUsage(volumeName);
- if (usage.inUse && usage.containers?.length > 0) {
- usageWarning = m.volumes_backup_restore_in_use_warning({ count: usage.containers.length });
- }
- } catch {
+ const operationResult = await tryCatch(
+ (async () => {
+ const usage = await volumeService.getVolumeUsage(volumeName);
+ if (usage.inUse && usage.containers?.length > 0) {
+ usageWarning = m.volumes_backup_restore_in_use_warning({ count: usage.containers.length });
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
// Ignore errors checking usage
}
@@ -292,12 +328,17 @@
label: m.volumes_backups_restore(),
destructive: !!usageWarning || hasWorkspaceChanges,
action: async () => {
- try {
- const result = await volumeBackupService.restoreBackup(volumeName, backup.id);
- await onWorkspaceRestored?.();
- toast.success(m.volumes_backup_restore_success(), activityToastOptions(extractActivityId(result)));
- await loadData(requestOptions);
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await volumeBackupService.restoreBackup(volumeName, backup.id);
+ await onWorkspaceRestored?.();
+ toast.success(m.volumes_backup_restore_success(), activityToastOptions(extractActivityId(result)));
+ await loadData(requestOptions);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
toast.error(error instanceof Error ? error.message : m.common_failed());
}
}
@@ -312,15 +353,22 @@
const selection = { paths: [...selectedPaths], selectAll: selectAllBackupFiles };
restoringFiles = true;
try {
- const result = await volumeBackupService.restoreBackupFiles(volumeName, restoreTarget.id, {
- ...selection,
- search: selection.selectAll ? backupFilesSearch.trim() : undefined
- });
- await onWorkspaceRestored?.();
- toast.success(m.volumes_backup_restore_selection_success(), activityToastOptions(extractActivityId(result)));
- showRestoreFiles = false;
- } catch (error) {
- toast.error(error instanceof Error ? error.message : m.common_failed());
+ const operationResult = await tryCatch(
+ (async () => {
+ const result = await volumeBackupService.restoreBackupFiles(volumeName, restoreTarget.id, {
+ ...selection,
+ search: selection.selectAll ? backupFilesSearch.trim() : undefined
+ });
+ await onWorkspaceRestored?.();
+ toast.success(m.volumes_backup_restore_selection_success(), activityToastOptions(extractActivityId(result)));
+ showRestoreFiles = false;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_failed());
+ }
} finally {
restoringFiles = false;
}
@@ -333,7 +381,9 @@
onMount(async () => {
const [collection, destinations] = await Promise.all([
volumeBackupService.getPolicies(volumeName),
- canBackupVolume ? s3DestinationService.listAll().catch(() => []) : Promise.resolve([]),
+ canBackupVolume
+ ? tryCatch(s3DestinationService.listAll()).then((result) => (result.error ? [] : result.data))
+ : Promise.resolve([]),
loadData(requestOptions)
]);
backupPolicies = collection.policies;
diff --git a/frontend/src/routes/(app)/volumes/volume-table.svelte b/frontend/src/routes/(app)/volumes/volume-table.svelte
index 017ae2ce7..0c7ed227a 100644
--- a/frontend/src/routes/(app)/volumes/volume-table.svelte
+++ b/frontend/src/routes/(app)/volumes/volume-table.svelte
@@ -7,7 +7,7 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
- import { tryCatch } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import { formatDateTimeShort, truncateString } from '#lib/utils/formatting.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { VolumeSummaryDto, VolumeSizeInfo } from '#lib/types/docker.js';
@@ -116,19 +116,25 @@
sizesLoading = true;
}
try {
- const sizes = await volumeService.getVolumeSizes(environmentId);
- if (currentEnvId !== environmentId || columnVisibility['size'] === false) return;
-
- sizesMap.clear();
- for (const s of sizes) {
- sizesMap.set(s.name, s);
- }
+ const operationResult = await tryCatch(
+ (async () => {
+ const sizes = await volumeService.getVolumeSizes(environmentId);
+ if (currentEnvId !== environmentId || columnVisibility['size'] === false) return;
+
+ sizesMap.clear();
+ for (const s of sizes) {
+ sizesMap.set(s.name, s);
+ }
- if (requestOptions?.sort?.column === 'size') {
- await refreshVolumes(requestOptions, false);
+ if (requestOptions?.sort?.column === 'size') {
+ await refreshVolumes(requestOptions, false);
+ }
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+ console.error('Failed to load volume sizes:', error);
}
- } catch (error) {
- console.error('Failed to load volume sizes:', error);
} finally {
sizeLoadPromises.delete(environmentId);
if (currentEnvId === environmentId) {
@@ -152,7 +158,7 @@
destructive: true,
action: async () => {
isLoading.removing = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(volumeService.deleteVolume(safeName)),
message: m.common_remove_failed({ resource: `${m.resource_volume()} "${safeName}"` }),
setLoadingState: (value) => (isLoading.removing = value),
@@ -179,7 +185,7 @@
if (!volumeToRename) return;
const oldName = volumeToRename.name;
isLoading.renaming = true;
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: await tryCatch(volumeService.renameVolume(oldName, { name: newName }, renameEnvironmentId)),
message: m.volumes_rename_failed({ name: oldName }),
setLoadingState: (value) => (isLoading.renaming = value),
diff --git a/frontend/src/routes/(auth)/login/+page.ts b/frontend/src/routes/(auth)/login/+page.ts
index b9325440b..9cd3ba048 100644
--- a/frontend/src/routes/(auth)/login/+page.ts
+++ b/frontend/src/routes/(auth)/login/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { redirect } from '@sveltejs/kit';
import { getEffectiveLandingPage } from '#lib/utils/navigation.js';
import { passkeyService } from '#lib/services/passkey-service.js';
@@ -16,7 +17,9 @@ export const load = async ({ parent, url }) => {
throw redirect(302, redirectTo || getEffectiveLandingPage());
}
- const passkeyAvailability = await passkeyService.getLoginAvailability().catch(() => null);
+ const passkeyAvailability = await tryCatch(passkeyService.getLoginAvailability()).then((result) =>
+ result.error ? null : result.data
+ );
const error = url.searchParams.get('error');
const errorMessage =
diff --git a/frontend/src/routes/(auth)/logout/+page.ts b/frontend/src/routes/(auth)/logout/+page.ts
index a09b40574..c6096f6ec 100644
--- a/frontend/src/routes/(auth)/logout/+page.ts
+++ b/frontend/src/routes/(auth)/logout/+page.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { redirect } from '@sveltejs/kit';
import type { PageLoad } from './$types';
import { authService } from '#lib/services/auth-service.js';
@@ -5,12 +6,17 @@ import { authService } from '#lib/services/auth-service.js';
export const load: PageLoad = async ({ fetch, parent }) => {
const { queryClient } = await parent();
- try {
- await fetch('/api/auth/logout', {
- method: 'POST',
- credentials: 'include'
- });
- } catch (error) {
+ const operationResult = await tryCatch(
+ (async () => {
+ await fetch('/api/auth/logout', {
+ method: 'POST',
+ credentials: 'include'
+ });
+ })()
+ );
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
console.error('Logout error:', error);
}
diff --git a/frontend/src/routes/(auth)/mobile/passkey/+page.svelte b/frontend/src/routes/(auth)/mobile/passkey/+page.svelte
index 83859f672..22a81edaf 100644
--- a/frontend/src/routes/(auth)/mobile/passkey/+page.svelte
+++ b/frontend/src/routes/(auth)/mobile/passkey/+page.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
import {
browserSupportsWebAuthn,
startAuthentication,
@@ -71,30 +72,36 @@
status = 'working';
await tick();
- try {
- let credential: MobilePasskeyCredential;
- if (request.operation === 'authenticate') {
- credential = await startAuthentication({
- optionsJSON: request.options as unknown as PublicKeyCredentialRequestOptionsJSON
- });
- if (request.mobileLogin) {
- const completion = await passkeyService.finishMobileLogin(
- request.mobileLogin.ceremonyId,
- credential,
- request.mobileLogin.codeChallenge
- );
- returnToArcaneMobile(makeMobilePasskeyLoginCallback(request.state, completion.transactionId));
- return;
+ const ceremonyRequest = request;
+ const ceremonyResult = await tryCatch(
+ (async () => {
+ let credential: MobilePasskeyCredential;
+ if (ceremonyRequest.operation === 'authenticate') {
+ credential = await startAuthentication({
+ optionsJSON: ceremonyRequest.options as unknown as PublicKeyCredentialRequestOptionsJSON
+ });
+ if (ceremonyRequest.mobileLogin) {
+ const completion = await passkeyService.finishMobileLogin(
+ ceremonyRequest.mobileLogin.ceremonyId,
+ credential,
+ ceremonyRequest.mobileLogin.codeChallenge
+ );
+ returnToArcaneMobile(makeMobilePasskeyLoginCallback(ceremonyRequest.state, completion.transactionId));
+ return;
+ }
+ } else {
+ credential = await startRegistration({
+ optionsJSON: ceremonyRequest.options as unknown as PublicKeyCredentialCreationOptionsJSON
+ });
}
- } else {
- credential = await startRegistration({
- optionsJSON: request.options as unknown as PublicKeyCredentialCreationOptionsJSON
- });
- }
- returnToArcaneMobile(makeMobilePasskeySuccessCallback(request.state, credential));
- } catch (error) {
- returnToArcaneMobile(makeMobilePasskeyErrorCallback(request.state, classifyMobilePasskeyError(error)));
+ returnToArcaneMobile(makeMobilePasskeySuccessCallback(ceremonyRequest.state, credential));
+ })()
+ );
+ if (ceremonyResult.error !== null) {
+ returnToArcaneMobile(
+ makeMobilePasskeyErrorCallback(ceremonyRequest.state, classifyMobilePasskeyError(ceremonyResult.error))
+ );
}
}
diff --git a/frontend/src/routes/(auth)/oidc/callback/+page.svelte b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
index c174644ce..406ae1901 100644
--- a/frontend/src/routes/(auth)/oidc/callback/+page.svelte
+++ b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
import { onMount } from 'svelte';
import { goto, refreshAll } from '$app/navigation';
import { page } from '$app/state';
@@ -51,13 +53,18 @@
// (with a graceful catch). We don't fetch them here directly — a user with
// zero/limited permissions would 403 on settings:read and crash this handler.
await refreshAll();
- try {
- const settings = await queryClient.fetchQuery({
- queryKey: queryKeys.settings.global(),
- queryFn: () => settingsService.getSettings()
- });
- settingsStore.set(settings);
- } catch (settingsError) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const settings = await queryClient.fetchQuery({
+ queryKey: queryKeys.settings.global(),
+ queryFn: () => settingsService.getSettings()
+ });
+ settingsStore.set(settings);
+ })()
+ );
+ if (operationResult.error !== null) {
+ const settingsError = operationResult.error;
+
// User lacks settings:read or settings fetch failed — not fatal; the root
// layout already pulls public settings as a fallback.
console.warn('Skipping post-login settings fetch:', settingsError);
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index c2dae19dc..2cfe456a2 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -12,7 +12,7 @@ import { type AppVersionInformation } from '#lib/types/settings.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { PermissionsManifest } from '#lib/types/auth.js';
import { authService } from '#lib/services/auth-service.js';
-import { tryCatch } from '#lib/utils/api.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
import { QueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
import { redirect } from '@sveltejs/kit';
@@ -45,7 +45,10 @@ export const load: LayoutLoad = async ({ url }) => {
queryFn: () => authService.getAutoLoginConfig()
})
: Promise.resolve(null);
- let [user, autoLoginConfig] = await Promise.all([userService.getCurrentUser().catch(() => null), autoLoginConfigRequest]);
+ let [user, autoLoginConfig] = await Promise.all([
+ tryCatch(userService.getCurrentUser()).then((result) => (result.error ? null : result.data)),
+ autoLoginConfigRequest
+ ]);
if (autoLoginConfig) {
if (autoLoginConfig.enabled) {
@@ -83,7 +86,9 @@ export const load: LayoutLoad = async ({ url }) => {
};
const environmentsRequest = tryCatch(environmentManagementService.getEnvironments(environmentRequestOptions));
- const permissionsManifestRequest = roleService.getPermissionsManifest().catch((): PermissionsManifest | null => null);
+ const permissionsManifestRequest = tryCatch(roleService.getPermissionsManifest()).then((result) =>
+ result.error ? null : result.data
+ );
const environments = await environmentsRequest;
if (!environments.error) {
await environmentStore.initialize(environments.data.data);
@@ -92,11 +97,15 @@ export const load: LayoutLoad = async ({ url }) => {
}
const settingsRequest = userHasPermission(user, 'settings:read')
- ? settingsService.getSettings().catch(() => settingsService.getPublicSettings().catch(() => null))
- : settingsService.getPublicSettings().catch(() => null);
+ ? tryCatch(settingsService.getSettings()).then(async (result) => {
+ if (!result.error) return result.data;
+ const publicSettings = await tryCatch(settingsService.getPublicSettings());
+ return publicSettings.error ? null : publicSettings.data;
+ })
+ : tryCatch(settingsService.getPublicSettings()).then((result) => (result.error ? null : result.data));
const [loadedSettings, loadedSwarmStatus, loadedPermissionsManifest] = await Promise.all([
settingsRequest,
- swarmService.getSwarmStatus().catch(() => null),
+ tryCatch(swarmService.getSwarmStatus()).then((result) => (result.error ? null : result.data)),
permissionsManifestRequest
]);
settings = loadedSettings;
@@ -108,7 +117,7 @@ export const load: LayoutLoad = async ({ url }) => {
await environmentStore.initialize([]);
// Try to fetch public settings for login page configuration
- settings = await settingsService.getPublicSettings().catch(() => null);
+ settings = await tryCatch(settingsService.getPublicSettings()).then((result) => (result.error ? null : result.data));
}
if (user) {
@@ -133,29 +142,31 @@ export const load: LayoutLoad = async ({ url }) => {
isSemverVersion: false
};
- try {
- const info = await versionInformationRequest;
- versionInformation = {
- currentVersion: info.currentVersion,
- currentTag: info.currentTag,
- currentDigest: info.currentDigest,
- displayVersion: info.displayVersion,
- revision: info.revision,
- shortRevision: info.shortRevision || (info.revision?.slice(0, 8) ?? 'unknown'),
- goVersion: info.goVersion || 'unknown',
- nodeVersion: info.nodeVersion || 'unknown',
- svelteKitVersion: info.svelteKitVersion || 'unknown',
- enabledFeatures: info.enabledFeatures ?? [],
- buildTime: info.buildTime,
- isSemverVersion: info.isSemverVersion,
- newestVersion: info.newestVersion,
- newestDigest: info.newestDigest,
- updateAvailable: info.updateAvailable,
- releaseUrl: info.releaseUrl,
- releaseNotes: info.releaseNotes,
- releasedAt: info.releasedAt
- };
- } catch {}
+ await tryCatch(
+ (async () => {
+ const info = await versionInformationRequest;
+ versionInformation = {
+ currentVersion: info.currentVersion,
+ currentTag: info.currentTag,
+ currentDigest: info.currentDigest,
+ displayVersion: info.displayVersion,
+ revision: info.revision,
+ shortRevision: info.shortRevision || (info.revision?.slice(0, 8) ?? 'unknown'),
+ goVersion: info.goVersion || 'unknown',
+ nodeVersion: info.nodeVersion || 'unknown',
+ svelteKitVersion: info.svelteKitVersion || 'unknown',
+ enabledFeatures: info.enabledFeatures ?? [],
+ buildTime: info.buildTime,
+ isSemverVersion: info.isSemverVersion,
+ newestVersion: info.newestVersion,
+ newestDigest: info.newestDigest,
+ updateAvailable: info.updateAvailable,
+ releaseUrl: info.releaseUrl,
+ releaseNotes: info.releaseNotes,
+ releasedAt: info.releasedAt
+ };
+ })()
+ );
const redirectPath = getAuthRedirectPath(
url.pathname,
diff --git a/frontend/src/service-worker/index.ts b/frontend/src/service-worker/index.ts
index be5f24fc3..b7cde330c 100644
--- a/frontend/src/service-worker/index.ts
+++ b/frontend/src/service-worker/index.ts
@@ -1,3 +1,4 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
import { version } from '$app/env';
import { assets } from '$app/manifest';
import { asset } from '$app/paths';
@@ -74,11 +75,8 @@ self.addEventListener('fetch', (event) => {
return cachedResponse;
}
- try {
- return await fetch(event.request);
- } catch {
- return new Response(null, { status: 503 });
- }
+ const result = await tryCatch(fetch(event.request));
+ return result.data ?? new Response(null, { status: 503 });
}
event.respondWith(respond());
diff --git a/tests/spec/containers.spec.ts b/tests/spec/containers.spec.ts
index 369bcf833..29a77c732 100644
--- a/tests/spec/containers.spec.ts
+++ b/tests/spec/containers.spec.ts
@@ -137,15 +137,25 @@ test.describe('Containers Page', () => {
});
test('should display stat cards with correct counts', async ({ page }) => {
- await navigateToContainers(page);
-
- const total = containersData.pagination?.totalItems ?? containersData.data.length;
- const running = containersData.data.filter((c) => c.state === 'running').length;
- const stopped = containersData.data.filter((c) => c.state !== 'running').length;
+ // Aggregate counts can exceed the current page and must not depend on other workers' containers.
+ const counts = { totalContainers: 37, runningContainers: 23, stoppedContainers: 14 };
+ await page.route(
+ (url) => /^\/api\/environments\/[^/]+\/containers$/.test(url.pathname),
+ async (route) => {
+ const response = await route.fetch();
+ const body = (await response.json()) as Record<string, unknown>;
+ await route.fulfill({ response, json: { ...body, counts } });
+ }
+ );
- await expect(page.getByText(`${total} Total`)).toBeVisible();
- await expect(page.getByText(`${running} Running`, { exact: true })).toBeVisible();
- await expect(page.getByText(`${stopped} Stopped`)).toBeVisible();
+ await navigateToContainers(page);
+ await expect(page.getByText(`${counts.totalContainers} Total`, { exact: true })).toBeVisible();
+ await expect(
+ page.getByText(`${counts.runningContainers} Running`, { exact: true })
+ ).toBeVisible();
+ await expect(
+ page.getByText(`${counts.stoppedContainers} Stopped`, { exact: true })
+ ).toBeVisible();
});
test('should display the container table with columns', async ({ page }) => {