From e4619ac766972d7c45822efe968c1bfa17a24a6c Mon Sep 17 00:00:00 2001 From: Erez Rokah Date: Thu, 8 Aug 2024 16:52:09 +0200 Subject: [PATCH] refactor: Early return in case of a connection error (#389) #### Summary The usual pattern in go is to do `if err != nil { // do something }`. The current code is a bit confusing to read as it does `if err == nil { return err }`. A smaller change can be to do `if err == nil { return nil }` --- --- managedplugin/plugin.go | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/managedplugin/plugin.go b/managedplugin/plugin.go index c7f89a5..c966d76 100644 --- a/managedplugin/plugin.go +++ b/managedplugin/plugin.go @@ -484,23 +484,19 @@ func (c *Client) startLocalUnixSocket(ctx context.Context, path string) error { c.wg.Add(1) go c.readLogLines(reader) - err = c.connectToUnixSocket(ctx) - // N.B. we exit early if connecting succeeds here! - if err == nil { - return nil - } - - // Error scenarios: + if err := c.connectToUnixSocket(ctx); err != nil { + if killErr := cmd.Process.Kill(); killErr != nil { + c.logger.Error().Err(killErr).Msg("failed to kill plugin process") + } - if killErr := cmd.Process.Kill(); killErr != nil { - c.logger.Error().Err(killErr).Msg("failed to kill plugin process") + waitErr := cmd.Wait() + if waitErr != nil && errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("failed to run plugin %s: %w", path, waitErr) + } + return fmt.Errorf("failed connecting to plugin %s: %w", path, err) } - waitErr := cmd.Wait() - if waitErr != nil && errors.Is(err, context.DeadlineExceeded) { - return fmt.Errorf("failed to run plugin %s: %w", path, waitErr) - } - return fmt.Errorf("failed connecting to plugin %s: %w", path, err) + return nil } func (c *Client) getPluginArgs() []string {