Skip to content

Commit

Permalink
add example for package gerror
Browse files Browse the repository at this point in the history
  • Loading branch information
gqcn committed Jun 15, 2022
1 parent 7d5ab1f commit 481c50f
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
6 changes: 6 additions & 0 deletions errors/gerror/gerror.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,9 @@ func Code(err error) gcode.Code {
if e, ok := err.(iNext); ok {
return Code(e.Next())
}
if e, ok := err.(iUnwrap); ok {
return Code(e.Unwrap())
}
return gcode.CodeNil
}

Expand All @@ -236,6 +239,9 @@ func Cause(err error) error {
if e, ok := err.(iNext); ok {
return Cause(e.Next())
}
if e, ok := err.(iUnwrap); ok {
return Cause(e.Unwrap())
}
return err
}

Expand Down
6 changes: 6 additions & 0 deletions errors/gerror/gerror_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,9 @@ type iNext interface {
Error() string
Next() error
}

// iUnwrap is the interface for Unwrap feature.
type iUnwrap interface {
Error() string
Unwrap() error
}
27 changes: 27 additions & 0 deletions errors/gerror/gerror_z_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,30 @@ func ExampleWrapCodef() {
// It's Custom Error: permission denied
// 10000
}

func ExampleEqual() {
err1 := errors.New("permission denied")
err2 := gerror.New("permission denied")
err3 := gerror.NewCode(gcode.CodeNotAuthorized, "permission denied")
fmt.Println(gerror.Equal(err1, err2))
fmt.Println(gerror.Equal(err2, err3))

// Output:
// true
// false
}

func ExampleIs() {
err1 := errors.New("permission denied")
err2 := gerror.Wrap(err1, "operation failed")
fmt.Println(gerror.Is(err1, err1))
fmt.Println(gerror.Is(err2, err2))
fmt.Println(gerror.Is(err2, err1))
fmt.Println(gerror.Is(err1, err2))

// Output:
// false
// true
// true
// false
}

0 comments on commit 481c50f

Please sign in to comment.