Skip to content

Commit e3826e5

Browse files
authored
Merge pull request #13 from golage/feature/casting-errors
feat: implements error casting
2 parents 89a6cbd + 267425b commit e3826e5

2 files changed

Lines changed: 88 additions & 0 deletions

File tree

errors.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,26 @@ func Wrap(cause error, code Code, message string, args ...interface{}) Fundament
3737
return fnd
3838
}
3939

40+
// Cast returns new instance fundamental error with error cause and code
41+
func Cast(err error, code Code) Fundamental {
42+
parsed, _ := Parse(err)
43+
if parsed == nil {
44+
return nil
45+
}
46+
if code == CodeNil {
47+
return nil
48+
}
49+
fnd := &fundamental{
50+
code: code,
51+
message: parsed.Message(),
52+
stackTrace: parsed.StackTrace(),
53+
}
54+
if fnd.stackTrace == nil {
55+
fnd.stackTrace = stacktrace.Capture(1)
56+
}
57+
return fnd
58+
}
59+
4060
// Parse returns fundamental error and code from all of error types
4161
func Parse(err error) (Fundamental, Code) {
4262
switch err := err.(type) {

errors_test.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,3 +267,71 @@ func TestWrap(t *testing.T) {
267267
})
268268
}
269269
}
270+
271+
func TestCast(t *testing.T) {
272+
type args struct {
273+
err error
274+
code Code
275+
}
276+
tests := []struct {
277+
name string
278+
args args
279+
want Fundamental
280+
}{
281+
{
282+
name: "must returns nil with nil err",
283+
args: args{
284+
err: nil,
285+
code: CodePermissionDenied,
286+
},
287+
want: nil,
288+
},
289+
{
290+
name: "must returns nil with nil code",
291+
args: args{
292+
err: fmt.Errorf("error"),
293+
code: CodeNil,
294+
},
295+
want: nil,
296+
},
297+
{
298+
name: "must returns fundamental from built-in error",
299+
args: args{
300+
err: fmt.Errorf("error"),
301+
code: CodeUnimplemented,
302+
},
303+
want: &fundamental{
304+
code: CodeUnimplemented,
305+
message: "error",
306+
stackTrace: stacktrace.Capture(0),
307+
},
308+
},
309+
{
310+
name: "must returns fundamental from fundamental error with new code",
311+
args: args{
312+
err: New(CodeAlreadyExists, "error"),
313+
code: CodeUnimplemented,
314+
},
315+
want: &fundamental{
316+
code: CodeUnimplemented,
317+
message: "error",
318+
stackTrace: stacktrace.Capture(0),
319+
},
320+
},
321+
}
322+
for _, tt := range tests {
323+
t.Run(tt.name, func(t *testing.T) {
324+
err := Cast(tt.args.err, tt.args.code)
325+
if tt.want == nil {
326+
assert.Equal(t, err, nil)
327+
} else {
328+
assert.Equal(t, err.Error(), tt.want.Error())
329+
assert.Equal(t, err.Message(), tt.want.Message())
330+
assert.Equal(t, int(err.Code()), int(tt.want.Code()))
331+
if tt.want.StackTrace() != nil {
332+
assert.Equal(t, err.StackTrace()[1:], tt.want.StackTrace()[1:])
333+
}
334+
}
335+
})
336+
}
337+
}

0 commit comments

Comments
 (0)