errors.go73 lines, 2.3 KB
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "log/slog" |
| 6 | "net/http" |
| 7 | |
| 8 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 9 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 10 | "google.golang.org/genproto/googleapis/rpc/errdetails" |
| 11 | "google.golang.org/grpc/codes" |
| 12 | "google.golang.org/grpc/status" |
| 13 | ) |
| 14 | |
| 15 | // Errors the gateway answers with itself. |
| 16 | var ( |
| 17 | errRateLimited = httpx.NewError(http.StatusTooManyRequests, "rate_limited", |
| 18 | "too many requests, try again after Retry-After seconds") |
| 19 | errUpstreamTimeout = httpx.NewError(http.StatusGatewayTimeout, "upstream_timeout", |
| 20 | "the service took too long to answer") |
| 21 | errUpstreamDown = httpx.NewError(http.StatusBadGateway, "upstream_unavailable", |
| 22 | "the service is unavailable, try again later") |
| 23 | ) |
| 24 | |
| 25 | // fromCode maps the gRPC codes our services send. Others are a 500. |
| 26 | var fromCode = map[codes.Code]struct { |
| 27 | status int |
| 28 | code string |
| 29 | }{ |
| 30 | codes.InvalidArgument: {http.StatusUnprocessableEntity, "invalid_input"}, |
| 31 | codes.FailedPrecondition: {http.StatusUnprocessableEntity, "failed_precondition"}, |
| 32 | codes.NotFound: {http.StatusNotFound, "not_found"}, |
| 33 | codes.AlreadyExists: {http.StatusConflict, "conflict"}, |
| 34 | codes.Aborted: {http.StatusConflict, "request_in_progress"}, |
| 35 | codes.Unauthenticated: {http.StatusUnauthorized, "unauthenticated"}, |
| 36 | codes.PermissionDenied: {http.StatusForbidden, "forbidden"}, |
| 37 | } |
| 38 | |
| 39 | // fromRPC turns a gRPC error into one httpx.Error sends with the right |
| 40 | // status: the mirror image of grpcx.ToStatus. |
| 41 | func fromRPC(err error) error { |
| 42 | s, ok := status.FromError(err) |
| 43 | if err == nil || !ok { |
| 44 | return err |
| 45 | } |
| 46 | switch s.Code() { |
| 47 | case codes.DeadlineExceeded: |
| 48 | return errUpstreamTimeout |
| 49 | case codes.Unavailable: |
| 50 | // Its message names addresses, and TLS errors: for our logs only. |
| 51 | slog.Warn("wallet unavailable", "err", s.Message()) |
| 52 | return errUpstreamDown |
| 53 | } |
| 54 | to, known := fromCode[s.Code()] |
| 55 | if !known { |
| 56 | return fmt.Errorf("rpc: %s: %s", s.Code(), s.Message()) |
| 57 | } |
| 58 | for _, d := range s.Details() { |
| 59 | switch d := d.(type) { |
| 60 | case *errdetails.BadRequest: |
| 61 | var v apperr.ValidationError |
| 62 | for _, f := range d.GetFieldViolations() { |
| 63 | v.Add(f.GetField(), f.GetDescription()) |
| 64 | } |
| 65 | if err := v.Err(); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | case *errdetails.ErrorInfo: |
| 69 | to.code = d.GetReason() |
| 70 | } |
| 71 | } |
| 72 | return httpx.NewError(to.status, to.code, s.Message()) |
| 73 | } |