0

我最近开始使用 Go 学习微服务,并且偶然发现了一些使用 micro、gRPC 和 protobuf 的教程。一段时间后,我意识到我没有收到来自为与微服务通信而创建的 cli 的任何错误消息。下面的代码能够重现这一点。


import (
    "context"
    "errors"
    "github.com/asim/go-micro/v3/client"
    "github.com/asim/go-micro/v3/cmd"
    "github.com/asim/go-micro/v3/logger"
    pb "github.com/dbielecki97/grpc-errors/proto/greeter"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    "log"
    "os"
)

func main() {

    err := cmd.Init(cmd.Name("cli.greeter"))
    if err != nil {
        return
    }

    log.Println(os.Args)

    if len(os.Args) < 2 {
        log.Fatal(errors.New("Not enough arguments, expecing name."))
    }

    name := os.Args[1]
    c := pb.NewGreeterService("service.greeter", client.DefaultClient)

    greet, err := c.Greet(context.Background(), &pb.Request{Name: name})
    if err != nil {
        s, ok := status.FromError(err)
        if ok {
            if s.Code() == codes.InvalidArgument {
                logger.Fatal("Incorrect name!")
            }
        } else {
            logger.Fatal(s.Message())
        }

    }

    logger.Info(greet.Message)

    os.Exit(0)
}

import (
    "context"
    "github.com/asim/go-micro/v3"
    "github.com/asim/go-micro/v3/logger"
    pb "github.com/dbielecki97/grpc-errors/proto/greeter"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

type greeterservice struct{}

func (g greeterservice) Greet(ctx context.Context, req *pb.Request, res *pb.Greeting) error {
    logger.Info("Name :: ", req.Name)
    if req.Name == "Dawid" {
        logger.Info("Correct name")
        res.Message = "Hello Dawid"
        return nil
    }
    logger.Warn("Incorrect name")
    return status.Error(codes.InvalidArgument, "Bad name")
}

func main() {
    service := micro.NewService(micro.Name("service.greeter"),
        micro.Version("latest"))
    service.Init()

    err := pb.RegisterGreeterServiceHandler(service.Server(), &greeterservice{})
    if err != nil {
        return
    }

    err = service.Run()
    if err != nil {
        return
    }
}
syntax = "proto3";

package greeter;

service GreeterService {
  rpc Greet(Request) returns (Greeting) {}

}

message Request {
  string name = 1;
}

message Greeting{
  string message = 1;
}

当客户端使用参数Dawid运行时,一切都按预期工作,但是如果我尝试其他任何操作,我确实希望客户端出现错误并显示消息Bad name,但我收到的只是默认 5 秒等待时间后的超时。

2021-05-31 16:26:36  file=client/client.go:40 level=fatal {"id":"go.micro.client","code":408,"detail":"call timeout: context deadline exceeded","status":"Request Timeout"}

回购链接:https ://github.com/dbielecki97/grpc-errors

4

1 回答 1

0

通过更新 protoc & protoc-gen-go 版本解决了我用这个

// protoc-gen-go v1.27.1

// 协议 v3.14.0

你可以试试这个或高版本

于 2021-08-31T17:39:30.670 回答