diff options
author | Jonathan Amsterdam <jba@google.com> | 2019-06-28 19:20:04 -0400 |
---|---|---|
committer | Jonathan Amsterdam <jba@google.com> | 2019-08-25 00:27:25 +0000 |
commit | 739123c3a36f30af06c294741f74a26e54ee21ad (patch) | |
tree | 51d65e322596da2047b6cb6b386105f5cb496c96 /src/errors | |
parent | 66ff373911a87140319a6550e4e1b2c6043b1329 (diff) | |
download | go-739123c3a36f30af06c294741f74a26e54ee21ad.tar.gz go-739123c3a36f30af06c294741f74a26e54ee21ad.zip |
errors: add example showing a custom error with Unwrap
Change-Id: I2bddee9b460d3875911859b49528a00d318f37fc
Reviewed-on: https://go-review.googlesource.com/c/go/+/184237
Reviewed-by: Russ Cox <rsc@golang.org>
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
Diffstat (limited to 'src/errors')
-rw-r--r-- | src/errors/example_unwrap_test.go | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/src/errors/example_unwrap_test.go b/src/errors/example_unwrap_test.go new file mode 100644 index 0000000000..05c9cd466f --- /dev/null +++ b/src/errors/example_unwrap_test.go @@ -0,0 +1,56 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors_test + +import ( + "errors" + "fmt" + "os" + "time" +) + +// MyError2 is an error implementation that includes a time, a message, and an +// underlying error. +type MyError2 struct { + When time.Time + What string + err error +} + +func (e MyError2) Error() string { + return fmt.Sprintf("%v at %v: %v", e.What, e.When, e.err) +} + +// Unwrap returns e's underlying error, or nil if there is none. +func (e MyError2) Unwrap() error { + return e.err +} + +func readConfig() error { + if _, err := os.Open("non-existing"); err != nil { + return MyError2{ + time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC), + "reading config file", + err, + } + } + return nil +} + +func Example_unwrap() { + if err := readConfig(); err != nil { + // Display the error. + fmt.Println(err) + // If we can retrieve the path, try to recover + // by taking another action. + var pe *os.PathError + if errors.As(err, &pe) { + restoreFile(pe.Path) + } + } + // Output: reading config file at 1989-03-15 22:30:00 +0000 UTC: open non-existing: no such file or directory +} + +func restoreFile(path string) {} |