LoginSignup
13
8

More than 3 years have passed since last update.

xerrorsへの移行手順

Last updated at Posted at 2019-03-01

xerrorsへの移行手順

https://github.com/pkg/errors を利用している前提で紹介します。

Go 1.13以降はスタックトレースの表示が不要でエラーのラップ機能だけでよければ、xerrorsを使う必要はなく、errorsパッケージを使いましょう。

基本

errors.New を xerrors.Newに変更

errors.New("message")
xerrors.New("message")

errors.Wrap(err, "") を xerrors.Errorf(": %w", err)に変更

errors.Wrap(err, "message")
xerrors.Errorf("message: %w", err)

fmt.Errorf を xerrors.Errorfに変更

fmt.Errorf("message: %v", msg)
xerrors.Errorf("message: %v", msg)

errors.Cause を xerrors.Unwrap に変更

err = errors.Cause(err)
err = xerrors.Unwrap(err)

エラーの値の比較をxerrors.Isに変更

err = errors.Cause(err)
if err == ErrNotFound {

}
// Unwrapは不要
if xerrors.Is(err, ErrNotFound) {

}

type assertion を Asに変更

if myErr, ok := err.(*MyError); ok {

}
var myErr *MyError
if ok := xerrors.As(err, &retErr); ok {

}

応用

fmt.Formatterをxerrors.ErrorFormatterに変更

func (e *Error) Format(s fmt.State, v rune) {

}
func (e *Error) Format(s fmt.State, v rune) {
    xerrors.FormatError(e, s, v)
}

func (e *Error) FormatError(p xerrors.Printer) (next error) {
    p.Print(e.Error())
    e.frame.Format(p)
    return e.err
}

最終確認

errorsが見つからないことを確認します。

$ grep -r "errors" ./

その他

エラー出力でスタックトレースを表示

err := func1()
fmt.Printf("%+v", err)

関連情報

13
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
8