Use status.Error or status.Errorf at a gRPC endpoint boundary so failures carry a gRPC status code and message. Endpoint returns should otherwise return nil errors. section 10.3.2
Translate known domain failures such as InvalidInputError into codes.InvalidArgument; format unexpected failures with codes.Internal and useful context. section 10.3.2
Mapping a habit-creation failure
got, err := habit.Create(ctx, h) if err != nil { var invalidErr habit.InvalidInputError if errors.As(err, &invalidErr) { return nil, status.Error(codes.InvalidArgument, invalidErr.Error()) } return nil, status.Errorf(codes.Internal, "cannot save habit %v: %s", h, err.Error()) }
Listing 10.18 create.go: Error management
got, err := habit.Create(ctx, h)
if err != nil {
var invalidErr habit.InvalidInputError
if errors.As(err, &invalidErr) {
return nil, status.Error(codes.InvalidArgument, invalidErr.Error())
}
// other error
return nil, status.Errorf(codes.Internal, "cannot save habit %v: %s",
h, err.Error())
}
Inspect the complete endpoint error branch, including errors.As, status.Error, status.Errorf, and the selected gRPC codes. section 10.3.2
