Skip to content

Commit

Permalink
Fix error handling when server fails to start
Browse files Browse the repository at this point in the history
Also make the ClientRaw.Close method more robust.
  • Loading branch information
bep committed Aug 20, 2022
1 parent da870b6 commit bed19df
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
20 changes: 16 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func StartClientRaw(opts ClientRawOptions) (*ClientRaw, error) {
}

if err := conn.Start(); err != nil {
return nil, fmt.Errorf("failed start server: %s: %s", err, conn.stdErr.String())
return nil, fmt.Errorf("failed to start server: %s: %s", err, conn.stdErr.String())
}

if opts.OnMessage == nil {
Expand Down Expand Up @@ -152,10 +152,22 @@ type ClientRaw struct {

// Close closes the server connection and waits for the server process to quit.
func (c *ClientRaw) Close() error {
if err := c.conn.Close(); err != nil {
return c.addErrContext("close", err)
if c == nil {
return nil
}
return nil
c.sendMu.Lock()
defer c.sendMu.Unlock()
c.mu.Lock()
defer c.mu.Unlock()

if c.closing {
return ErrShutdown
}
c.closing = true

err := c.conn.Close()

return err
}

// Execute sends body to the server and returns the Message it receives.
Expand Down
15 changes: 15 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,21 @@ func TestExecRaw(t *testing.T) {
c.Assert(err, qt.IsNil)
c.Assert(string(result.Body), qt.Equals, "echo: hello")
})
}

func TestExecStartFailed(t *testing.T) {
c := qt.New(t)
client, err := execrpc.StartClientRaw(
execrpc.ClientRawOptions{
Version: 1,
Cmd: "go",
Dir: "./examples/servers/doesnotexist",
Args: []string{"run", "."},
})

c.Assert(err, qt.IsNotNil)
c.Assert(err.Error(), qt.Contains, "failed to start server: chdir ./examples/servers/doesnotexist")
c.Assert(client.Close(), qt.IsNil)

}

Expand Down
2 changes: 1 addition & 1 deletion conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (c conn) Close() error {
func (c conn) Start() error {
err := c.cmd.Start()
if err != nil {
return c.Close()
return err
}

ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
Expand Down

0 comments on commit bed19df

Please sign in to comment.