Skip to content

Instantly share code, notes, and snippets.

@m-mizutani
Created May 22, 2022 01:19
Show Gist options
  • Save m-mizutani/40adbb04779211ef6aa96046a1f7a0c8 to your computer and use it in GitHub Desktop.
Save m-mizutani/40adbb04779211ef6aa96046a1f7a0c8 to your computer and use it in GitHub Desktop.
構造化エラーハンドリングのサンプル
package main
import (
"errors"
"github.com/m-mizutani/goerr"
"github.com/rs/zerolog/log"
)
type Request struct {
Method string
Path string
Value string
}
func handler(req *Request) error {
if req.Method != "GET" {
// Newするとスタックトレースが保存される & With(key, value) で関連する変数を保存する
return goerr.New("invalid method").With("req", req)
}
// something to do
return nil
}
func main() {
req := &Request{
Method: "POST",
Path: "/hello",
Value: "blue",
}
if err := handler(req); err != nil {
var goErr *goerr.Error
if errors.As(err, &goErr) {
// errors.As で特定のエラー型だった場合のみ処理する
log.Error().
Interface("values", goErr.Values()).
Interface("stacktrace", goErr.Stacks()).
Msg(err.Error())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment