Skip to content

Instantly share code, notes, and snippets.

@wer14
Last active February 16, 2024 10:21
Show Gist options
  • Save wer14/a90b1666917412e47b2c5dd4a05b2acc to your computer and use it in GitHub Desktop.
Save wer14/a90b1666917412e47b2c5dd4a05b2acc to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
pb "main/errortest"
"main/hater"
"reflect"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
conn, err := grpc.Dial("localhost:9090", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return
}
defer conn.Close()
client := pb.NewErrorTestClient(conn)
_, err = client.ErrorTest(context.Background(), &pb.EmptyMsg{})
if err != nil {
fmt.Println(reflect.TypeOf(&err).Elem())
if h, ok := err.(hat.Hat); ok { //Can't cast to hat.Hat interface
h.Show()
}
}
}
package hat
import "fmt"
type Hat interface {
Show()
error
}
type CustomError struct {
Message string
}
func (e CustomError) Show() {
fmt.Println(e.Message)
}
func (e CustomError) Error() string {
return e.Message
}
package main
import (
"context"
"fmt"
"log"
"net"
"google.golang.org/grpc"
pb "main/errortest"
"main/hater"
)
type ErrorTestServer struct {
pb.UnimplementedErrorTestServer
}
func (s ErrorTestServer) ErrorTest(ctx context.Context, _ *pb.EmptyMsg) (*pb.StatusMsg, error) {
return &pb.StatusMsg{}, NewCustomError()
}
func NewCustomError() hater.CustomError {
return hater.CustomError{
Message: "Greetings from Bali!",
}
}
func main() {
lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 9090))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
pb.RegisterErrorTestServer(grpcServer, ErrorTestServer{})
if err := grpcServer.Serve(lis); err != nil {
fmt.Print("failed to start server")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment