Skip to content

Commit 67b523f

Browse files
committed
Better error handling
1 parent 944163a commit 67b523f

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

err.go

+11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package tcp
22

33
import (
44
"errors"
5+
"syscall"
56
)
67

78
// ErrTimeout indicates I/O timeout
@@ -15,3 +16,13 @@ type timeoutError struct{}
1516
func (e *timeoutError) Error() string { return "I/O timeout" }
1617
func (e *timeoutError) Timeout() bool { return true }
1718
func (e *timeoutError) Temporary() bool { return true }
19+
20+
// ErrConnect is an error occurs while connecting to the host
21+
// To get the detail of underlying error, lookup ErrorCode() in 'man 2 connect'
22+
type ErrConnect struct {
23+
syscall.Errno
24+
}
25+
26+
func newErrConnect(errCode int) *ErrConnect {
27+
return &ErrConnect{syscall.Errno(errCode)}
28+
}

shaker.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@
3131
package tcp
3232

3333
import (
34-
"fmt"
3534
"os"
3635
"runtime"
3736
"sync"
@@ -97,12 +96,12 @@ func (s *Shaker) Test(addr string, timeout time.Duration) error {
9796
// check for connect error
9897
for {
9998
succeed, err := s.wait(fd, timeoutMS)
100-
if err != nil {
101-
return fmt.Errorf("connect error: %s", err)
102-
}
10399
if reached(deadline) {
104100
return ErrTimeout
105101
}
102+
if err != nil {
103+
return err
104+
}
106105
if succeed {
107106
return nil
108107
}
@@ -170,7 +169,7 @@ func (s *Shaker) wait(fd int, timeoutMS int) (bool, error) {
170169
return false, os.NewSyscallError("getsockopt", err)
171170
}
172171
if errCode != 0 {
173-
return false, fmt.Errorf("getsockopt[%d]", errCode)
172+
return false, newErrConnect(errCode)
174173
}
175174
return true, nil
176175
}

shaker_test.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ func ExampleShaker() {
2020
case nil:
2121
fmt.Println("Connect to Google succeded")
2222
default:
23-
fmt.Println("Connect to Google failed:", err)
23+
if e, ok := err.(*ErrConnect); ok {
24+
fmt.Println("Connect to Google failed:", e)
25+
} else {
26+
fmt.Println("Error occurred while connecting:", err)
27+
}
2428
}
2529
}

0 commit comments

Comments
 (0)