Skip to content

Commit ba950b9

Browse files
committed
refactor: refactor error handling in withCode and withMessage
Removed redundant struct nesting in `withCode` and streamlined test cases in `TestNew`. Updated error formatting logic for clearer output and added missing method implementations. Improved test assertions and optimized error message comparisons.
1 parent ef6ab15 commit ba950b9

File tree

5 files changed

+87
-74
lines changed

5 files changed

+87
-74
lines changed

README.md

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ func ReturnNil() error {
3131
func main() {
3232
err := OpenFile()
3333
fmt.Printf("%+v\n", err)
34-
fmt.Println("------------")
34+
fmt.Println("\n------------\n")
35+
36+
fmt.Printf("%v\n", err)
37+
fmt.Println("\n------------\n")
3538

3639
err = ReturnNil()
3740
fmt.Printf("%+v\n", err)
@@ -49,7 +52,13 @@ runtime.main
4952
/usr/local/go/src/runtime/proc.go:250
5053
runtime.goexit
5154
/usr/local/go/src/runtime/asm_amd64.s:1571
55+
56+
------------
57+
58+
open ./test.err: no such file or directory
59+
5260
------------
61+
5362
<nil>
5463

5564
```
@@ -66,7 +75,7 @@ import (
6675

6776
func A() error {
6877
_, err := os.Open("./test.err")
69-
return errors.WithStack(err)
78+
return errors.Wrap(err, "failed to open file")
7079
}
7180

7281
func B() error {
@@ -82,13 +91,17 @@ func C() error {
8291
func main() {
8392
err := C()
8493
fmt.Printf("%+v\n", err)
94+
fmt.Println("\n------------\n")
95+
96+
fmt.Printf("%v\n", err)
8597
}
8698

8799
```
88100

89101
Output:
90102
```
91103
open ./test.err: no such file or directory
104+
failed to open file
92105
main.A
93106
/go/src/test/err/main.go:11
94107
main.B
@@ -100,7 +113,11 @@ main.main
100113
runtime.main
101114
/usr/local/go/src/runtime/proc.go:250
102115
runtime.goexit
103-
/usr/local/go/src/runtime/asm_amd64.s:157
116+
/usr/local/go/src/runtime/asm_amd64.s:1571
117+
118+
------------
119+
120+
failed to open file -> {open ./test.err: no such file or directory}
104121
```
105122

106123
## Error code
@@ -161,11 +178,11 @@ Output:
161178
```
162179
error code: 400102030
163180
error msg: invalid params
164-
error err: [400102030: invalid params] -> {param: id: 1 -> {[500201010: user not found] -> {record not found}}}
181+
error err: [400102030: invalid params] -> {[500201010: user not found] -> {param: id: 1 -> {record not found}}}
165182
---------------------
166183
record not found
167-
500201010: user not found
168184
param: id: 1
185+
500201010: user not found
169186
main.SqlFirst
170187
/go/src/test/err/main.go:27
171188
main.Server

README_CN.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -140,21 +140,21 @@ func main() {
140140
// Output:
141141
// error code: 400102030
142142
// error msg: invalid params
143-
// error err: [400102030: invalid params] -> {param: id: 1 -> {[500201010: user not found] -> {record not found}}}
143+
// error err: [400102030: invalid params] -> {[500201010: user not found] -> {param: id: 1 -> {record not found}}}
144144
// ---------------------
145145
// record not found
146-
// 500201010: user not found
147146
// param: id: 1
147+
// 500201010: user not found
148148
// main.SqlFirst
149-
// /go/src/test/err/main.go:27
149+
// /go/src/test/err/main.go:27
150150
// main.Server
151-
// /go/src/test/err/main.go:31
151+
// /go/src/test/err/main.go:31
152152
// main.main
153-
// /go/src/test/err/main.go:43
153+
// /go/src/test/err/main.go:43
154154
// runtime.main
155-
// /usr/local/go/src/runtime/proc.go:250
155+
// /usr/local/go/src/runtime/proc.go:250
156156
// runtime.goexit
157-
// /usr/local/go/src/runtime/asm_amd64.s:1571
157+
// /usr/local/go/src/runtime/asm_amd64.s:1571
158158
// 400102030: invalid params
159159
```
160160

error.go

Lines changed: 37 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,14 @@ func (w *withMessage) Wrapf(err error, format string, args ...any) error {
6666
if err == nil {
6767
return nil
6868
}
69-
wm := &withMessage{
70-
message: w.Message(),
69+
wm := withMessage{
70+
message: fmt.Sprintf(format, args...),
7171
cause: err,
7272
}
7373
ws := &withStack{
7474
error: &withMessage{
75-
message: fmt.Sprintf(format, args...),
76-
cause: wm,
75+
message: w.message,
76+
cause: &wm,
7777
},
7878
}
7979
if !stackExists(ws) {
@@ -104,26 +104,37 @@ type ErrorCode interface {
104104
}
105105

106106
type withCode struct {
107-
*withMessage
108-
code int
107+
code int
108+
message string
109+
cause error
109110
}
110111

111112
func (w *withCode) Code() int {
112113
return w.code
113114
}
114115

116+
func (w *withCode) Message() string {
117+
return w.message
118+
}
119+
120+
func (w *withCode) Cause() error {
121+
return w.cause
122+
}
123+
124+
func (w *withCode) Unwrap() error {
125+
return w.cause
126+
}
127+
115128
// WrapStack If err is nil, WithStack returns nil.
116129
func (w *withCode) WrapStack(err error) error {
117130
if err == nil {
118131
return nil
119132
}
120133
ws := &withStack{
121134
error: &withCode{
122-
withMessage: &withMessage{
123-
message: w.Message(),
124-
cause: err,
125-
},
126-
code: w.Code(),
135+
code: w.code,
136+
message: w.message,
137+
cause: err,
127138
},
128139
}
129140
if !stackExists(ws) {
@@ -137,19 +148,17 @@ func (w *withCode) Wrapf(err error, format string, args ...any) error {
137148
if err == nil {
138149
return nil
139150
}
140-
wm := &withMessage{
141-
message: w.Message(),
151+
wm := withMessage{
152+
message: fmt.Sprintf(format, args...),
142153
cause: err,
143154
}
144-
wc := &withCode{
145-
withMessage: wm,
146-
code: w.Code(),
155+
wc := withCode{
156+
code: w.code,
157+
message: w.message,
158+
cause: &wm,
147159
}
148160
ws := &withStack{
149-
error: &withMessage{
150-
message: fmt.Sprintf(format, args...),
151-
cause: wc,
152-
},
161+
error: &wc,
153162
}
154163
if !stackExists(ws) {
155164
ws.stack = callers()
@@ -158,11 +167,11 @@ func (w *withCode) Wrapf(err error, format string, args ...any) error {
158167
}
159168

160169
func (w *withCode) Error() string {
161-
s := fmt.Sprintf("[%d: %s]", w.Code(), w.Message())
162-
if w.Cause() == nil {
170+
s := fmt.Sprintf("[%d: %s]", w.code, w.message)
171+
if w.cause == nil {
163172
return s
164173
}
165-
return fmt.Sprintf("%s -> {%s}", s, w.Cause())
174+
return fmt.Sprintf("%s -> {%s}", s, w.cause)
166175
}
167176

168177
func (w *withCode) Is(err error) bool {
@@ -176,10 +185,10 @@ func (w *withCode) Format(s fmt.State, verb rune) {
176185
switch verb {
177186
case 'v':
178187
if s.Flag('+') {
179-
if w.Cause() != nil {
180-
fmt.Fprintf(s, "%+v\n", w.Cause())
188+
if w.cause != nil {
189+
fmt.Fprintf(s, "%+v\n", w.cause)
181190
}
182-
fmt.Fprintf(s, "%d: %s", w.Code(), w.Message())
191+
fmt.Fprintf(s, "%d: %s", w.code, w.message)
183192
return
184193
}
185194
fallthrough
@@ -273,10 +282,8 @@ func NewWithMessage(format string, args ...any) ErrorMessage {
273282
// NewWithCode no stack
274283
func NewWithCode(code int, format string, args ...any) ErrorCode {
275284
return &withCode{
276-
code: code,
277-
withMessage: &withMessage{
278-
message: fmt.Sprintf(format, args...),
279-
},
285+
code: code,
286+
message: fmt.Sprintf(format, args...),
280287
}
281288
}
282289

error_test.go

Lines changed: 19 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -27,40 +27,31 @@ var (
2727
)
2828

2929
func TestNew(t *testing.T) {
30-
type args struct {
31-
format string
32-
}
3330
tests := []struct {
3431
name string
35-
args args
36-
wantErr error
32+
input string
33+
wantErr string
3734
}{
3835
{
39-
"new abc - fmt.Errorf",
40-
args{
41-
format: "abc",
42-
},
43-
fmt.Errorf("abc"),
44-
},
45-
{
46-
"new abc - errors.New",
47-
args{
48-
format: "abc",
49-
},
50-
errors.New("abc"),
36+
name: "new abc",
37+
input: "abc",
38+
wantErr: "abc",
5139
},
5240
{
53-
"new abc",
54-
args{
55-
format: "abc",
56-
},
57-
New("abc"),
41+
name: "empty string",
42+
input: "",
43+
wantErr: "",
5844
},
5945
}
6046
for _, tt := range tests {
6147
t.Run(tt.name, func(t *testing.T) {
62-
if err := New(tt.args.format); err.Error() != tt.wantErr.Error() {
63-
t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
48+
err := New(tt.input)
49+
if err == nil {
50+
t.Errorf("New() returned nil, want error")
51+
return
52+
}
53+
if err.Error() != tt.wantErr {
54+
t.Errorf("New() error = %v, want %v", err.Error(), tt.wantErr)
6455
}
6556
})
6657
}
@@ -94,10 +85,8 @@ func TestNewWithCode(t *testing.T) {
9485
args: []any{"bbb"},
9586
},
9687
&withCode{
97-
withMessage: &withMessage{
98-
message: "aaa: bbb",
99-
},
100-
code: 100,
88+
code: 100,
89+
message: "aaa: bbb",
10190
},
10291
},
10392
{
@@ -107,8 +96,8 @@ func TestNewWithCode(t *testing.T) {
10796
format: "",
10897
},
10998
&withCode{
110-
withMessage: &withMessage{},
111-
code: 200,
99+
code: 200,
100+
message: "",
112101
},
113102
},
114103
}

example_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -309,8 +309,8 @@ func ExampleLatestMessage() {
309309
// Output:
310310
//ErrUserNotFound: user not found
311311
//ErrInvalidParams: invalid params
312-
//latestErr: param <123> -> {invalid params -> {user not found}}
313-
//otherErr: service err -> {param <123> -> {invalid params -> {user not found}}}
312+
//latestErr: invalid params -> {param <123> -> {user not found}}
313+
//otherErr: service err -> {invalid params -> {param <123> -> {user not found}}}
314314
}
315315

316316
func ExampleIs_code() {

0 commit comments

Comments
 (0)