Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gRPC Error Wrapper #7

Open
sinmetal opened this issue Oct 21, 2020 · 3 comments
Open

gRPC Error Wrapper #7

sinmetal opened this issue Oct 21, 2020 · 3 comments

Comments

@sinmetal
Copy link
Member

WHAT

gRPCのerrorをいい感じにWrapする方法を考える。
選択肢的には以下のどちらか。
どっちもどっちみたいな気持ち

fmt.Errorf(": %w" err) でwrapしたものを剥いて、status.Status を取り出す

以下のようなやつ

func UnwrapGRPCError(err error) (*status.Status, bool) {
	cerr := err
	for {
		sts, ok := status.FromError(cerr)
		if ok {
			return sts, true
		}
		nerr := errors.Unwrap(cerr)
		if nerr == nil {
			return nil, false
		}
		cerr = nerr
	}
}

https://github.com/sinmetal/til/blob/51fd3cc40761e95b77dee6168be5d436d7cc1f7e/datastore/tx/cloud_datastore_service.go#L45

status.Status を内包する Custom Error を作る

WHY

gRPC の error は Wrap すると、gRPC package の関数では取り出せない

@sinmetal
Copy link
Member Author

自分で https://github.com/grpc/grpc-go/blob/9519efffeb5d1897ae8671568871a6d476986524/status/status.go#L83-L85 に合致するinterfaceを作ってしまうという手もあるらしい

package main
import (
	"errors"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)
type gRPCStatus interface {
	GRPCStatus() *status.Status
}
func main() {
	// original gRPC error
	err := status.Errorf(codes.Unauthenticated, "unauthenticated")
	// wrapping
	nerr := fmt.Errorf("wrapping: %w", err)
	nerr = fmt.Errorf("more wrapping: %w", nerr)
	var e gRPCStatus
	if errors.As(nerr, &e) {
		fmt.Printf("code: %s \n", e.GRPCStatus().Code())
	} else {
		fmt.Println("not a gRPCStatus error")
	}
	// this prints "code: Unauthenticated"
}

@sinmetal
Copy link
Member Author

errors.As() をサポートするissueはあるけど、まだ作られてはいない
grpc/grpc-go#2934

@sinmetal
Copy link
Member Author

sinmetal added a commit that referenced this issue Oct 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant