From 0ebb21f0fbd0a8a8d5abb7c3bc155317acb1876f Mon Sep 17 00:00:00 2001 From: Atterpac <89053530+atterpac@users.noreply.github.com> Date: Fri, 29 Nov 2024 19:36:29 -0700 Subject: [PATCH] [V3] Rework service.OnStartup to close application on error (#3920) * rework service.OnStartup to close applicatoin on error CHANGELOG.md fix index out of bounds potential * os.Exit -> runtime.Goexit * Revert to os.Exit --------- Co-authored-by: Lea Anthony --- mkdocs-website/docs/en/changelog.md | 1 + v3/pkg/application/application.go | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mkdocs-website/docs/en/changelog.md b/mkdocs-website/docs/en/changelog.md index cb0684f591b..166f4a09a68 100644 --- a/mkdocs-website/docs/en/changelog.md +++ b/mkdocs-website/docs/en/changelog.md @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 in [#3888](https://github.com/wailsapp/wails/pull/3888) ### Changed +- `service.OnStartup` now shutdowns the application on error and runs `service.OnShutdown`for any prior services that started by @atterpac in [#3920](https://github.com/wailsapp/wails/pull/3920) - Refactored systray click messaging to better align with user interactions by @atterpac in [#3907](https://github.com/wailsapp/wails/pull/3907) - Asset embed to include `all:frontend/dist` to support frameworks that generate subfolders by @atterpac in [#3887](https://github.com/wailsapp/wails/pull/3887) - Taskfile refactor by [leaanthony](https://github.com/leaanthony) in [#3748](https://github.com/wailsapp/wails/pull/3748) diff --git a/v3/pkg/application/application.go b/v3/pkg/application/application.go index 2f2f062da4a..33d47a70cfc 100644 --- a/v3/pkg/application/application.go +++ b/v3/pkg/application/application.go @@ -136,7 +136,7 @@ func New(appOptions Options) *App { result.handleFatalError(fmt.Errorf("Fatal error in application initialisation: " + err.Error())) } - for _, service := range appOptions.Services { + for i, service := range appOptions.Services { if thisService, ok := service.instance.(ServiceStartup); ok { err := thisService.OnStartup(result.ctx, service.options) if err != nil { @@ -144,8 +144,18 @@ func New(appOptions Options) *App { if name == "" { name = getServiceName(service.instance) } - globalApplication.Logger.Error("OnStartup() failed:", "service", name, "error", err.Error()) - continue + globalApplication.Logger.Error("OnStartup() failed shutting down application:", "service", name, "error", err.Error()) + // Run shutdown on all services that have already started + for _, service := range appOptions.Services[:i] { + if thisService, ok := service.instance.(ServiceShutdown); ok { + err := thisService.OnShutdown() + if err != nil { + globalApplication.Logger.Error("Error shutting down service: " + err.Error()) + } + } + } + // Shutdown the application + os.Exit(1) } } }