Navigation Menu

Skip to content

Commit

Permalink
Unwrap tests and readme
Browse files Browse the repository at this point in the history
  • Loading branch information
ztrue committed Feb 15, 2019
1 parent 7c8caea commit e8ec8d5
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 1 deletion.
16 changes: 15 additions & 1 deletion README.md
Expand Up @@ -59,7 +59,7 @@ Or:
err := tracerr.Errorf("some error %d", num)
```

### Add stack trace to existing error
### Add Stack Trace to Existing Error

> If `err` is `nil` then it still be `nil` with no stack trace added.
Expand Down Expand Up @@ -142,3 +142,17 @@ Or if `err` is of type `*tracerr.Error`:
```go
frames := err.StackTrace()
```

### Get Original Error

> Unwrapped error will be `nil` if `err` is `nil` and will be the same error if `err` is not an instance of `*tracerr.Error`.
```go
err = tracerr.Unwrap(err)
```

Or if `err` is of type `*tracerr.Error`:

```go
err = err.Unwrap()
```
12 changes: 12 additions & 0 deletions error.go
Expand Up @@ -40,6 +40,18 @@ func Wrap(err error) *Error {
return trace(err, 2)
}

// Unwrap returns the original error.
func Unwrap(err error) error {
if err == nil {
return nil
}
e, ok := err.(*Error)
if !ok {
return err
}
return e.Unwrap()
}

// Error returns error message.
func (e *Error) Error() string {
if e == nil {
Expand Down
35 changes: 35 additions & 0 deletions error_test.go
Expand Up @@ -206,3 +206,38 @@ func TestStackTraceNotInstance(t *testing.T) {
)
}
}

type UnwrapTestCase struct {
Error error
Wrap bool
}

func TestUnwrap(t *testing.T) {
cases := []UnwrapTestCase{
{
Error: nil,
},
{
Error: fmt.Errorf("some error #%d", 9),
Wrap: false,
},
{
Error: fmt.Errorf("some error #%d", 9),
Wrap: true,
},
}

for i, c := range cases {
err := c.Error
if c.Wrap {
err = tracerr.Wrap(err)
}
unwrappedError := tracerr.Unwrap(err)
if unwrappedError != c.Error {
t.Errorf(
"tracerr.Unwrap(cases[%#v].Error) = %#v; want %#v",
i, unwrappedError, c.Error,
)
}
}
}

0 comments on commit e8ec8d5

Please sign in to comment.