-
-
Save baijum/f285d701f5713f3836d8e004a162d178 to your computer and use it in GitHub Desktop.
Example of github.com/pkg/errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/pkg/errors" | |
) | |
func A() error { | |
// New errors created with pkg/errors.New() will include a full | |
// stack trace. | |
return errors.New("blam") | |
} | |
func B() error { | |
// No need to wrap/trace at every return, just a point of error | |
// creation. | |
return A() | |
} | |
func C() error { | |
// Pre-existing errors may be wrapped to add more detail. | |
return errors.Wrap(B(), "foo") | |
} | |
func D() error { | |
return C() | |
} | |
func main() { | |
err := D() | |
fmt.Printf("# Value:\n %v\n\n", err) | |
// Formatting with %+v produces stack trace. | |
fmt.Printf("# Extended value:\n%+v\n\n", err) | |
// errors.Cause() provides access to original error. | |
fmt.Printf("# Cause: %v\n", errors.Cause(err)) | |
fmt.Printf("# Extended Cause:\n%+v\n", errors.Cause(err)) | |
} | |
/* Example output: | |
# Value: | |
foo: blam | |
# Extended value: | |
blam | |
main.A | |
/home/menno/go/src/sandbox/errs/main.go:12 | |
main.B | |
/home/menno/go/src/sandbox/errs/main.go:18 | |
main.C | |
/home/menno/go/src/sandbox/errs/main.go:23 | |
main.D | |
/home/menno/go/src/sandbox/errs/main.go:27 | |
main.main | |
/home/menno/go/src/sandbox/errs/main.go:31 | |
runtime.main | |
/snap/go/327/src/runtime/proc.go:185 | |
runtime.goexit | |
/snap/go/327/src/runtime/asm_amd64.s:2197 | |
foo | |
main.C | |
/home/menno/go/src/sandbox/errs/main.go:23 | |
main.D | |
/home/menno/go/src/sandbox/errs/main.go:27 | |
main.main | |
/home/menno/go/src/sandbox/errs/main.go:31 | |
runtime.main | |
/snap/go/327/src/runtime/proc.go:185 | |
runtime.goexit | |
/snap/go/327/src/runtime/asm_amd64.s:2197 | |
# Cause: blam | |
# Extended Cause: | |
blam | |
main.A | |
/home/menno/go/src/sandbox/errs/main.go:12 | |
main.B | |
/home/menno/go/src/sandbox/errs/main.go:18 | |
main.C | |
/home/menno/go/src/sandbox/errs/main.go:23 | |
main.D | |
/home/menno/go/src/sandbox/errs/main.go:27 | |
main.main | |
/home/menno/go/src/sandbox/errs/main.go:31 | |
runtime.main | |
/snap/go/327/src/runtime/proc.go:185 | |
runtime.goexit | |
/snap/go/327/src/runtime/asm_amd64.s:2197 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment