Skip to content

Commit 168e5a2

Browse files
Add gRPC error handling
Add gRPC error handling
1 parent 6f9cce7 commit 168e5a2

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@
1313

1414
# Dependency directories (remove the comment below to include it)
1515
.idea/
16-
.vsode/
16+
.vsode/
17+
codiga.yml

api/data/products.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"fmt"
66
protos "github.com/evgeniy-dammer/building-microservices-with-go/currency/protos/currency"
77
"github.com/hashicorp/go-hclog"
8+
"google.golang.org/grpc/codes"
9+
"google.golang.org/grpc/status"
810
)
911

1012
// ErrProductNotFound error product not found
@@ -144,6 +146,22 @@ func (p *ProductsDB) getRate(destination string) (float64, error) {
144146

145147
// get initial rate
146148
resp, err := p.currency.GetRate(context.Background(), rr)
149+
if err != nil {
150+
if s, ok := status.FromError(err); !ok {
151+
md := s.Details()[0].(*protos.RateRequest)
152+
153+
if s.Code() == codes.InvalidArgument {
154+
return -1, fmt.Errorf("unable to get rate from currency server, destination and base currency can not be the same: base %s, dest %s",
155+
md.Base.String(), md.Destination.String(),
156+
)
157+
}
158+
159+
return -1, fmt.Errorf("unable to get rate from currency server: base %s, dest %s", md.Base.String(), md.Destination.String())
160+
}
161+
162+
return -1, err
163+
}
164+
147165
// update cache
148166
p.rates[destination] = float64(resp.Rate)
149167
// subscribe for updates

currency/server/currency.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"github.com/evgeniy-dammer/building-microservices-with-go/currency/data"
66
protos "github.com/evgeniy-dammer/building-microservices-with-go/currency/protos/currency"
77
"github.com/hashicorp/go-hclog"
8+
"google.golang.org/grpc/codes"
9+
"google.golang.org/grpc/status"
810
"io"
911
"time"
1012
)
@@ -54,6 +56,22 @@ func (c *Currency) handleUpdate() {
5456
func (c *Currency) GetRate(ctx context.Context, request *protos.RateRequest) (*protos.RateResponse, error) {
5557
c.log.Info("Handle GetRate", "base", request.GetBase(), "destination", request.GetDestination())
5658

59+
if request.Base == request.Destination {
60+
err := status.Newf(
61+
codes.InvalidArgument,
62+
"base currency %s can not be same as the destination currency %s",
63+
request.Base.String(), request.Destination.String(),
64+
)
65+
66+
err, wde := err.WithDetails(request)
67+
68+
if wde != nil {
69+
return nil, wde
70+
}
71+
72+
return nil, err.Err()
73+
}
74+
5775
rate, err := c.rates.GetRate(request.GetBase().String(), request.GetDestination().String())
5876

5977
if err != nil {

0 commit comments

Comments
 (0)