Skip to content

Commit ccd0b22

Browse files
author
keks
committed
add HandleError function to contain boilerplate
1 parent 514f13b commit ccd0b22

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

response.go

+23
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package cmds
22

33
import (
44
"fmt"
5+
"io"
56

67
"github.com/ipfs/go-ipfs-cmdkit"
78
)
@@ -36,3 +37,25 @@ func (h Head) Length() uint64 {
3637
func (h Head) Error() *cmdkit.Error {
3738
return h.Err
3839
}
40+
41+
// HandleError handles the error from cmds.Response.Next(), it returns
42+
// true if Next() should be called again
43+
func HandleError(err error, res Response, re ResponseEmitter) bool {
44+
if err != nil {
45+
if err == io.EOF {
46+
return false
47+
}
48+
49+
if err == ErrRcvdError {
50+
err = res.Error()
51+
}
52+
53+
if e, ok := err.(*cmdkit.Error); ok {
54+
re.SetError(e.Message, e.Code)
55+
} else {
56+
re.SetError(err, cmdkit.ErrNormal)
57+
}
58+
return false
59+
}
60+
return true
61+
}

response_test.go

+50
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,20 @@ type TestOutput struct {
1414
Baz int
1515
}
1616

17+
func eqStringSlice(a, b []string) bool {
18+
if len(a) != len(b) {
19+
return false
20+
}
21+
22+
for i := range a {
23+
if a[i] != b[i] {
24+
return false
25+
}
26+
}
27+
28+
return true
29+
}
30+
1731
func TestMarshalling(t *testing.T) {
1832
cmd := &Command{}
1933
opts, _ := cmd.GetOptions(nil)
@@ -50,6 +64,42 @@ func TestMarshalling(t *testing.T) {
5064
}
5165
}
5266

67+
func TestHandleError(t *testing.T) {
68+
var (
69+
out []string
70+
exp = []string{"1", "2", "3", "EOF"}
71+
)
72+
73+
cmd := &Command{}
74+
opts, _ := cmd.GetOptions(nil)
75+
76+
req, _ := NewRequest(nil, nil, nil, nil, nil, opts)
77+
78+
re, res := NewChanResponsePair(req)
79+
go func() {
80+
re.Emit(1)
81+
re.Emit(2)
82+
re.Emit(3)
83+
re.Close()
84+
}()
85+
86+
var err error
87+
for HandleError(err, res, re) {
88+
var v interface{}
89+
v, err = res.Next()
90+
if v != nil {
91+
out = append(out, fmt.Sprint(v))
92+
} else {
93+
out = append(out, fmt.Sprint(err))
94+
}
95+
96+
}
97+
98+
if !eqStringSlice(out, exp) {
99+
t.Fatalf("expected %v, got %v", exp, out)
100+
}
101+
}
102+
53103
func removeWhitespace(input string) string {
54104
input = strings.Replace(input, " ", "", -1)
55105
input = strings.Replace(input, "\t", "", -1)

0 commit comments

Comments
 (0)