|
| 1 | +package errorx_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/joomcode/errorx" |
| 6 | +) |
| 7 | + |
| 8 | +func ExampleDecorate() { |
| 9 | + err := someFunc() |
| 10 | + fmt.Println(err.Error()) |
| 11 | + |
| 12 | + err = errorx.Decorate(err, "decorate") |
| 13 | + fmt.Println(err.Error()) |
| 14 | + |
| 15 | + err = errorx.Decorate(err, "outer decorate") |
| 16 | + fmt.Println(err.Error()) |
| 17 | + |
| 18 | + // Output: common.assertion_failed: example |
| 19 | + // decorate, cause: common.assertion_failed: example |
| 20 | + // outer decorate, cause: decorate, cause: common.assertion_failed: example |
| 21 | +} |
| 22 | + |
| 23 | +func ExampleDecorateMany() { |
| 24 | + err0 := someFunc() |
| 25 | + err1 := someFunc() |
| 26 | + err := errorx.DecorateMany("both calls failed", err0, err1) |
| 27 | + fmt.Println(err.Error()) |
| 28 | + |
| 29 | + // Output: both calls failed, cause: common.assertion_failed: example (hidden: common.assertion_failed: example) |
| 30 | +} |
| 31 | + |
| 32 | +func ExampleError_WithUnderlyingErrors() { |
| 33 | + fn := func() error { |
| 34 | + bytes, err := getBodyAndError() |
| 35 | + if err != nil { |
| 36 | + _, unmarshalErr := getDetailsFromBody(bytes) |
| 37 | + if unmarshalErr != nil { |
| 38 | + return errorx.AssertionFailed.Wrap(err, "failed to read details").WithUnderlyingErrors(unmarshalErr) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return nil |
| 43 | + } |
| 44 | + |
| 45 | + fmt.Println(fn().Error()) |
| 46 | + // Output: common.assertion_failed: failed to read details, cause: common.assertion_failed: example (hidden: common.illegal_format) |
| 47 | +} |
| 48 | + |
| 49 | +func ExampleType_Wrap() { |
| 50 | + originalErr := errorx.IllegalArgument.NewWithNoMessage() |
| 51 | + err := errorx.AssertionFailed.Wrap(originalErr, "wrapped") |
| 52 | + |
| 53 | + fmt.Println(errorx.IsOfType(originalErr, errorx.IllegalArgument)) |
| 54 | + fmt.Println(errorx.IsOfType(err, errorx.IllegalArgument)) |
| 55 | + fmt.Println(errorx.IsOfType(err, errorx.AssertionFailed)) |
| 56 | + fmt.Println(err.Error()) |
| 57 | + |
| 58 | + // Output: |
| 59 | + // true |
| 60 | + // false |
| 61 | + // true |
| 62 | + // common.assertion_failed: wrapped, cause: common.illegal_argument |
| 63 | +} |
| 64 | + |
| 65 | +func someFunc() error { |
| 66 | + return errorx.AssertionFailed.New("example") |
| 67 | +} |
| 68 | + |
| 69 | +func getBodyAndError() ([]byte, error) { |
| 70 | + return nil, errorx.AssertionFailed.New("example") |
| 71 | +} |
| 72 | + |
| 73 | +func getDetailsFromBody(s []byte) (string, error) { |
| 74 | + return "", errorx.IllegalFormat.New(string(s)) |
| 75 | +} |
0 commit comments