Skip to content

Commit bed19df

Browse files
committed
Fix error handling when server fails to start
Also make the ClientRaw.Close method more robust.
1 parent da870b6 commit bed19df

3 files changed

Lines changed: 32 additions & 5 deletions

File tree

client.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ func StartClientRaw(opts ClientRawOptions) (*ClientRaw, error) {
106106
}
107107

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

112112
if opts.OnMessage == nil {
@@ -152,10 +152,22 @@ type ClientRaw struct {
152152

153153
// Close closes the server connection and waits for the server process to quit.
154154
func (c *ClientRaw) Close() error {
155-
if err := c.conn.Close(); err != nil {
156-
return c.addErrContext("close", err)
155+
if c == nil {
156+
return nil
157157
}
158-
return nil
158+
c.sendMu.Lock()
159+
defer c.sendMu.Unlock()
160+
c.mu.Lock()
161+
defer c.mu.Unlock()
162+
163+
if c.closing {
164+
return ErrShutdown
165+
}
166+
c.closing = true
167+
168+
err := c.conn.Close()
169+
170+
return err
159171
}
160172

161173
// Execute sends body to the server and returns the Message it receives.

client_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,21 @@ func TestExecRaw(t *testing.T) {
3333
c.Assert(err, qt.IsNil)
3434
c.Assert(string(result.Body), qt.Equals, "echo: hello")
3535
})
36+
}
37+
38+
func TestExecStartFailed(t *testing.T) {
39+
c := qt.New(t)
40+
client, err := execrpc.StartClientRaw(
41+
execrpc.ClientRawOptions{
42+
Version: 1,
43+
Cmd: "go",
44+
Dir: "./examples/servers/doesnotexist",
45+
Args: []string{"run", "."},
46+
})
47+
48+
c.Assert(err, qt.IsNotNil)
49+
c.Assert(err.Error(), qt.Contains, "failed to start server: chdir ./examples/servers/doesnotexist")
50+
c.Assert(client.Close(), qt.IsNil)
3651

3752
}
3853

conn.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ func (c conn) Close() error {
7575
func (c conn) Start() error {
7676
err := c.cmd.Start()
7777
if err != nil {
78-
return c.Close()
78+
return err
7979
}
8080

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

0 commit comments

Comments
 (0)