Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: handle frontend errors better to reduce 500 error codes (#1936)
Kyle Mendell7f2c75558653
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.goindex 785e6aeee..085ab0216 100644--- a/backend/internal/services/project_service.go+++ b/backend/internal/services/project_service.go@@ -474,19 +474,26 @@ func (s *ProjectService) enrichWithComposeServiceConfigs(ctx context.Context, prautoInjectEnv := s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false)composeProj, loadErr := projects.LoadComposeProject(ctx, composeFile, normalizeComposeProjectName(proj.Name), projectsDirectory, autoInjectEnv, pathMapper)- if loadErr == nil && composeProj != nil {- // Convert map to slice- svcList := make([]composetypes.ServiceConfig, 0, len(composeProj.Services))- hasBuildDirective := false- for _, svc := range composeProj.Services {- svcList = append(svcList, svc)- if svc.Build != nil {- hasBuildDirective = true- }+ if loadErr != nil {+ slog.WarnContext(ctx, "failed to load compose service configs", "path", composeFile, "error", loadErr)+ return+ }++ if composeProj == nil {+ return+ }++ // Convert map to slice+ svcList := make([]composetypes.ServiceConfig, 0, len(composeProj.Services))+ hasBuildDirective := false+ for _, svc := range composeProj.Services {+ svcList = append(svcList, svc)+ if svc.Build != nil {+ hasBuildDirective = true}- resp.Services = svcList- resp.HasBuildDirective = resp.HasBuildDirective || hasBuildDirective}+ resp.Services = svcList+ resp.HasBuildDirective = resp.HasBuildDirective || hasBuildDirective}func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error {@@ -1786,6 +1793,27 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, naswitch {case composeContent != nil:+ // Validate compose content before writing to disk to surface syntax errors early.+ // compose-go can panic on malformed inputs (e.g. invalid depends_on format), so we+ // catch both returned errors and panics here.+ var composeValidateErr error+ func() {+ defer func() {+ if r := recover(); r != nil {+ composeValidateErr = fmt.Errorf("compose file contains invalid syntax: %v", r)+ }+ }()+ cfg := composetypes.ConfigDetails{+ Version: api.ComposeVersion,+ ConfigFiles: []composetypes.ConfigFile{+ {Filename: "compose.yaml", Content: []byte(*composeContent)},+ },+ }+ _, composeValidateErr = loader.LoadWithContext(ctx, cfg)+ }()+ if composeValidateErr != nil {+ return nil, fmt.Errorf("invalid compose file: %w", composeValidateErr)+ }if err := fs.SaveOrUpdateProjectFiles(projectsDirectory, proj.Path, *composeContent, envContent); err != nil {return nil, fmt.Errorf("failed to save project files: %w", err)}diff --git a/backend/pkg/projects/load.go b/backend/pkg/projects/load.goindex 7c2cd84d6..9d8df604f 100644--- a/backend/pkg/projects/load.go+++ b/backend/pkg/projects/load.go@@ -64,7 +64,19 @@ func loadComposeProjectInternal(pathMapper *pathmapper.PathMapper,envOverride EnvMap,configureLoader func(*loader.Options),-) (*composetypes.Project, error) {+) (project *composetypes.Project, err error) {+ defer func() {+ if recovered := recover(); recovered != nil {+ slog.WarnContext(ctx,+ "panic while loading compose project; compose file may contain invalid syntax",+ "path", composeFile,+ "error", recovered,+ )+ err = fmt.Errorf("load compose project panic for %s: %v", composeFile, recovered)+ project = nil+ }+ }()+workdir := filepath.Dir(composeFile)projectsDir := projectsDirectory@@ -99,7 +111,7 @@ func loadComposeProjectInternal(Environment: composetypes.Mapping(fullEnvMap),}- project, err := loader.LoadWithContext(ctx, cfg, func(opts *loader.Options) {+ project, err = loader.LoadWithContext(ctx, cfg, func(opts *loader.Options) {if projectName != "" {opts.SetProjectName(projectName, true)}diff --git a/frontend/src/lib/utils/page-load-error.util.ts b/frontend/src/lib/utils/page-load-error.util.tsnew file mode 100644index 000000000..d3b2539f8--- /dev/null+++ b/frontend/src/lib/utils/page-load-error.util.ts@@ -0,0 +1,30 @@+import { error as kitError } from '@sveltejs/kit';+import { AxiosError } from 'axios';+import { extractApiErrorMessage } from './api.util';++export function extractApiErrorStatus(err: unknown, fallbackStatus = 500): number {+ if (err instanceof AxiosError) {+ return err.response?.status ?? fallbackStatus;+ }++ if (err && typeof err === 'object') {+ const maybeStatus = (err as { status?: unknown }).status;+ if (typeof maybeStatus === 'number' && Number.isFinite(maybeStatus)) {+ return maybeStatus;+ }+ if (typeof maybeStatus === 'string') {+ const parsed = Number.parseInt(maybeStatus, 10);+ if (!Number.isNaN(parsed)) {+ return parsed;+ }+ }+ }++ return fallbackStatus;+}++export function throwPageLoadError(err: unknown, fallbackMessage: string): never {+ const status = extractApiErrorStatus(err);+ const message = extractApiErrorMessage(err) || fallbackMessage;+ kitError(status, message);+}diff --git a/frontend/src/routes/(app)/containers/+page.ts b/frontend/src/routes/(app)/containers/+page.tsindex 944cb1f1d..55c773592 100644--- a/frontend/src/routes/(app)/containers/+page.ts+++ b/frontend/src/routes/(app)/containers/+page.ts@@ -5,6 +5,7 @@ import type { PageLoad } from './$types';import { settingsService } from '$lib/services/settings-service';import { environmentStore } from '$lib/stores/environment.store.svelte';import { queryKeys } from '$lib/query/query-keys';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';export const load: PageLoad = async ({ parent }) => {const { queryClient } = await parent();@@ -16,16 +17,22 @@ export const load: PageLoad = async ({ parent }) => {} satisfies SearchPaginationSortRequest);// containers includes counts, settings is separate- const [containers, settings] = await Promise.all([- queryClient.fetchQuery({- queryKey: queryKeys.containers.list(envId, containerRequestOptions),- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)- }),- queryClient.fetchQuery({- queryKey: queryKeys.settings.byEnvironment(envId),- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)- })- ]);+ let containers;+ let settings;+ try {+ [containers, settings] = await Promise.all([+ queryClient.fetchQuery({+ queryKey: queryKeys.containers.list(envId, containerRequestOptions),+ queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)+ }),+ queryClient.fetchQuery({+ queryKey: queryKeys.settings.byEnvironment(envId),+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)+ })+ ]);+ } catch (err) {+ throwPageLoadError(err, 'Failed to load containers');+ }return {containers,diff --git a/frontend/src/routes/(app)/dashboard/+page.ts b/frontend/src/routes/(app)/dashboard/+page.tsindex 50bbec9ee..54448129d 100644--- a/frontend/src/routes/(app)/dashboard/+page.ts+++ b/frontend/src/routes/(app)/dashboard/+page.ts@@ -6,6 +6,7 @@ import { systemService } from '$lib/services/system-service';import { environmentStore } from '$lib/stores/environment.store.svelte';import { queryKeys } from '$lib/query/query-keys';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';export const load: PageLoad = async ({ parent, url }) => {@@ -34,20 +35,27 @@ export const load: PageLoad = async ({ parent, url }) => {}};- const [containers, images, containerStatusCounts] = await Promise.all([- queryClient.fetchQuery({- queryKey: queryKeys.containers.list(envId, containerRequestOptions),- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)- }),- queryClient.fetchQuery({- queryKey: queryKeys.images.list(envId, imageRequestOptions),- queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)- }),- queryClient.fetchQuery({- queryKey: queryKeys.containers.statusCounts(envId),- queryFn: () => containerService.getContainerStatusCountsForEnvironment(envId)- })- ]);+ let containers;+ let images;+ let containerStatusCounts;+ try {+ [containers, images, containerStatusCounts] = await Promise.all([+ queryClient.fetchQuery({+ queryKey: queryKeys.containers.list(envId, containerRequestOptions),+ queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)+ }),+ queryClient.fetchQuery({+ queryKey: queryKeys.images.list(envId, imageRequestOptions),+ queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)+ }),+ queryClient.fetchQuery({+ queryKey: queryKeys.containers.statusCounts(envId),+ queryFn: () => containerService.getContainerStatusCountsForEnvironment(envId)+ })+ ]);+ } catch (err) {+ throwPageLoadError(err, 'Failed to load dashboard data');+ }const [dockerInfoResult, settingsResult, imageUsageCountsResult, dashboardActionItemsResult] = await Promise.allSettled([queryClient.fetchQuery({diff --git a/frontend/src/routes/(app)/environments/+page.ts b/frontend/src/routes/(app)/environments/+page.tsindex 41e4b0274..cf47bb559 100644--- a/frontend/src/routes/(app)/environments/+page.ts+++ b/frontend/src/routes/(app)/environments/+page.ts@@ -3,6 +3,7 @@ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import { environmentManagementService } from '$lib/services/env-mgmt-service';import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';import { queryKeys } from '$lib/query/query-keys';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';export const load: PageLoad = async ({ parent }) => {const { queryClient } = await parent();@@ -18,10 +19,15 @@ export const load: PageLoad = async ({ parent }) => {}} satisfies SearchPaginationSortRequest);- const environments = await queryClient.fetchQuery({- queryKey: queryKeys.environments.list(environmentRequestOptions),- queryFn: () => environmentManagementService.getEnvironments(environmentRequestOptions)- });+ let environments;+ try {+ environments = await queryClient.fetchQuery({+ queryKey: queryKeys.environments.list(environmentRequestOptions),+ queryFn: () => environmentManagementService.getEnvironments(environmentRequestOptions)+ });+ } catch (err) {+ throwPageLoadError(err, 'Failed to load environments');+ }return { environments, environmentRequestOptions };};diff --git a/frontend/src/routes/(app)/events/+page.ts b/frontend/src/routes/(app)/events/+page.tsindex 742b8f00f..b8db6f669 100644--- a/frontend/src/routes/(app)/events/+page.ts+++ b/frontend/src/routes/(app)/events/+page.ts@@ -2,6 +2,7 @@ import { eventService } from '$lib/services/event-service';import { queryKeys } from '$lib/query/query-keys';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';export const load: PageLoad = async ({ parent }) => {@@ -18,10 +19,15 @@ export const load: PageLoad = async ({ parent }) => {}} satisfies SearchPaginationSortRequest);- const events = await queryClient.fetchQuery({- queryKey: queryKeys.events.listGlobal(eventRequestOptions),- queryFn: () => eventService.getEvents(eventRequestOptions)- });+ let events;+ try {+ events = await queryClient.fetchQuery({+ queryKey: queryKeys.events.listGlobal(eventRequestOptions),+ queryFn: () => eventService.getEvents(eventRequestOptions)+ });+ } catch (err) {+ throwPageLoadError(err, 'Failed to load events');+ }return { events, eventRequestOptions };};diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.tsindex f872c00fa..c90a8af75 100644--- a/frontend/src/routes/(app)/images/+page.ts+++ b/frontend/src/routes/(app)/images/+page.ts@@ -3,6 +3,7 @@ import { settingsService } from '$lib/services/settings-service';import { queryKeys } from '$lib/query/query-keys';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';import { environmentStore } from '$lib/stores/environment.store.svelte';@@ -20,20 +21,27 @@ export const load: PageLoad = async ({ parent }) => {direction: 'desc'}} satisfies SearchPaginationSortRequest);- const [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)- })- ]);+ 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) {+ throwPageLoadError(err, 'Failed to load images');+ }return { images, imageRequestOptions, settings, imageUsageCounts };};diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.tsindex a22d7f02a..c907e760b 100644--- a/frontend/src/routes/(app)/networks/+page.ts+++ b/frontend/src/routes/(app)/networks/+page.ts@@ -2,6 +2,7 @@ import { networkService } from '$lib/services/network-service';import { queryKeys } from '$lib/query/query-keys';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';import { environmentStore } from '$lib/stores/environment.store.svelte';@@ -21,10 +22,15 @@ export const load: PageLoad = async ({ parent }) => {} satisfies SearchPaginationSortRequest);// Single API call - counts are included in the response- const networks = await queryClient.fetchQuery({- queryKey: queryKeys.networks.list(envId, networkRequestOptions),- queryFn: () => networkService.getNetworksForEnvironment(envId, networkRequestOptions)- });+ let networks;+ try {+ networks = await queryClient.fetchQuery({+ queryKey: queryKeys.networks.list(envId, networkRequestOptions),+ queryFn: () => networkService.getNetworksForEnvironment(envId, networkRequestOptions)+ });+ } catch (err) {+ throwPageLoadError(err, 'Failed to load networks');+ }return {networks,diff --git a/frontend/src/routes/(app)/projects/+page.ts b/frontend/src/routes/(app)/projects/+page.tsindex 03f0dc76f..864f8e0c9 100644--- a/frontend/src/routes/(app)/projects/+page.ts+++ b/frontend/src/routes/(app)/projects/+page.ts@@ -2,6 +2,7 @@ import { projectService } from '$lib/services/project-service';import { queryKeys } from '$lib/query/query-keys';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';import { environmentStore } from '$lib/stores/environment.store.svelte';@@ -20,16 +21,22 @@ export const load: PageLoad = async ({ parent }) => {}} satisfies SearchPaginationSortRequest);- const [projects, projectStatusCounts] = 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)- })- ]);+ let projects;+ let projectStatusCounts;+ try {+ [projects, projectStatusCounts] = 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)+ })+ ]);+ } catch (err) {+ throwPageLoadError(err, 'Failed to load projects');+ }return { projects, projectRequestOptions, projectStatusCounts };};diff --git a/frontend/src/routes/(app)/projects/[projectId]/+error.svelte b/frontend/src/routes/(app)/projects/[projectId]/+error.sveltenew file mode 100644index 000000000..e24b3a50f--- /dev/null+++ b/frontend/src/routes/(app)/projects/[projectId]/+error.svelte@@ -0,0 +1,32 @@+<script lang="ts">+ import { page } from '$app/state';+ import { goto } from '$app/navigation';+ import * as Empty from '$lib/components/ui/empty/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { AlertIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';++ const status = $derived(page.status ?? 500);+ const message = $derived(page.error?.message ?? m.error_generic());+</script>++<div class="flex h-full flex-1 flex-col items-center justify-center p-8">+ <Empty.Root>+ <Empty.Header>+ <Empty.Media variant="icon">+ <AlertIcon class="text-destructive size-16" aria-hidden="true" />+ </Empty.Media>+ <Empty.Title>+ {status === 404 ? m.error_not_found() : 'Failed to load project'}+ </Empty.Title>+ <Empty.Description>+ {message}+ </Empty.Description>+ </Empty.Header>+ <Empty.Content>+ <div class="flex flex-col items-center gap-3">+ <ArcaneButton action="base" customLabel="Back to Projects" onclick={() => goto('/projects')} />+ </div>+ </Empty.Content>+ </Empty.Root>+</div>diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.ts b/frontend/src/routes/(app)/projects/[projectId]/+page.tsindex b7d6e72f4..105c5d800 100644--- a/frontend/src/routes/(app)/projects/[projectId]/+page.ts+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.ts@@ -2,27 +2,39 @@ import { projectService } from '$lib/services/project-service';import { templateService } from '$lib/services/template-service';import { environmentStore } from '$lib/stores/environment.store.svelte';import { queryKeys } from '$lib/query/query-keys';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';+import type { QueryClient } from '@tanstack/svelte-query';import type { PageLoad } from './$types';+async function loadGlobalVariables(queryClient: QueryClient) {+ return queryClient+ .fetchQuery({+ queryKey: queryKeys.templates.globalVariables(),+ queryFn: () => templateService.getGlobalVariables()+ })+ .catch((err) => {+ console.warn('Failed to load global variables:', err);+ return [];+ });+}+export const load: PageLoad = async ({ params, parent }) => {const { queryClient } = await parent();const envId = await environmentStore.getCurrentEnvironmentId();- const [project, globalVariables] = await Promise.all([- queryClient.fetchQuery({+ 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)- }),- queryClient- .fetchQuery({- queryKey: queryKeys.templates.globalVariables(),- queryFn: () => templateService.getGlobalVariables()- })- .catch((err) => {- console.warn('Failed to load global variables:', err);- return [];- })- ]);+ });+ } catch (err) {+ throwPageLoadError(err, 'Failed to load project');+ }++ const globalVariables = await loadGlobalVariables(queryClient);const editorState = {name: project.name || '',@@ -38,6 +50,6 @@ export const load: PageLoad = async ({ params, parent }) => {project,editorState,globalVariables,- error: null+ error: null as string | null};};diff --git a/frontend/src/routes/(app)/security/+page.ts b/frontend/src/routes/(app)/security/+page.tsindex e79eb93d9..fc3060759 100644--- a/frontend/src/routes/(app)/security/+page.ts+++ b/frontend/src/routes/(app)/security/+page.ts@@ -5,6 +5,7 @@ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';import type { Paginated } from '$lib/types/pagination.type';import type { VulnerabilityWithImage } from '$lib/types/vulnerability.type';+import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {@@ -67,16 +68,22 @@ export const load: PageLoad = async ({ parent }) => {const requestForApi = mapVulnerabilityRequest(vulnerabilityRequestOptions);- const [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)- })- ]);+ 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) {+ throwPageLoadError(err, 'Failed to load security data');+ }return {summary,