Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Go 1.20で入った Wrapping multiple errorsをみてみる

Terry
March 08, 2023
64

Go 1.20で入った Wrapping multiple errorsをみてみる

3/8のSendai.go LT会の内容です
https://sendaigo.connpass.com/event/274874/

Terry

March 08, 2023
Tweet

Transcript

  1. Wrapping multiple errorsとは Go 1.20 expands support for error wrapping

    to permit an error to wrap multiple other errors. An error e can wrap more than one error by providing an Unwrap method that returns a []error. The errors.Is and errors.As functions have been updated to inspect multiply wrapped errors. The fmt.Errorf function now supports multiple occurrences of the %w format verb, which will cause it to return an error that wraps all of those error operands. The new function errors.Join returns an error wrapping a list of errors. https://tip.golang.org/doc/go1.20#errors
  2. Wrapping multiple errorsとは • Go 1.20から追加された機能 • 複数のerrorをまとめることができる ◦ []error

    を返す Unwrap メソッドが必要 • errors.Is()とerrors.As()がmulti errorにも使えるよ • fmt.Errorf()とerrors.Join()で作成できるよ 結構記事出ているからすでに聞いた人も多いかも .... https://go.dev/play/p/D2uoyxvFDM-
  3. fmt.Errorf()とerrors.Join()の違いは? • Error()を呼んだ時の出力の仕方が違っている ◦ fmt.Errorf()は組み立てたメッセージ ◦ errors.Join()は改行入りのerrorをそれぞれ出す • Unwrap()は同じものが返る errors.Join()

    https://cs.opensource.google/go/go/+/refs/tags/g o1.20rc3:src/errors/join.go;l=34-51 fmt.Errorf() https://cs.opensource.google/go/go/+/refs/tags/go 1.20rc3:src/fmt/errors.go;l=67-78;bpv=0;bpt=1