Skip to content

Commit f47f2fa

Browse files
authored
Merge pull request #722 from devlights:add-go120-multiple-w-verb
Add Go 1.20 wrap multiple errors example
2 parents e55a656 + e77e0a8 commit f47f2fa

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

examples/basic/errs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@
99
| error\_typeassertion.go | error\_typeassertion | Goにおけるエラー処理イディオムの type assertion check についてのサンプルです. |
1010
| error\_wrap\_unwrap.go | error\_wrap\_unwrap | Goにおけるエラー処理にてエラーを内包するやり方についてのサンプルです。 |
1111
| error\_is\_and\_as.go | error\_is\_and\_as | errors.Is(), errors.As() のサンプルです。 |
12+
| error\_wrap\_multiple\_error.go | error\_wrap\_multiple\_error | Go 1.20 で導入された %w を複数指定できるようになった機能のサンプルです。 |
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package errs
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
7+
"github.com/devlights/gomy/output"
8+
)
9+
10+
type _wmErr struct {
11+
m string
12+
}
13+
14+
type _wmErr2 struct {
15+
}
16+
17+
func (me *_wmErr) Error() string {
18+
return me.m
19+
}
20+
21+
func (me *_wmErr2) Error() string {
22+
return ""
23+
}
24+
25+
// WrapMultipleError は、Go 1.20 で導入された %w を複数指定できるようになった機能のサンプルです。
26+
//
27+
// # REFERENCES
28+
// - https://future-architect.github.io/articles/20230126a/
29+
// - https://tip.golang.org/doc/go1.20#errors
30+
func WrapMultipleError() error {
31+
//
32+
// Go 1.20 で、 %w を複数指定できるようになった
33+
//
34+
var (
35+
e1 = errors.New("error 1")
36+
e2 = errors.New("error 2")
37+
e3 = &_wmErr{m: "error 3"}
38+
)
39+
40+
e4 := fmt.Errorf("%w,%w,%w", e1, e2, e3)
41+
output.Stdoutf("[e4]", "%T: %v\n", e4, e4)
42+
43+
//
44+
// errors.Is でちゃんと判定される
45+
//
46+
output.Stdoutl("[Is(e4, e2)]", errors.Is(e4, e2))
47+
48+
//
49+
// errors.As でちゃんと判定される
50+
//
51+
var wme *_wmErr
52+
var wme2 *_wmErr2
53+
output.Stdoutl("[As(e4, &wme) ]", errors.As(e4, &wme))
54+
output.Stdoutl("[As(e4, &wme2)]", errors.As(e4, &wme2))
55+
56+
return nil
57+
}

examples/basic/errs/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2121
m["error_join"] = ErrorJoin
2222
m["error_join_fmt_errorf"] = ErrorJoinFmtErrorf
2323
m["error_join_errors_as"] = ErrorJoinErrorsAs
24+
m["error_wrap_multiple_error"] = WrapMultipleError
2425
}

0 commit comments

Comments
 (0)