-
Notifications
You must be signed in to change notification settings - Fork 1
/
error.go
49 lines (39 loc) · 1.16 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package middleware
import (
"context"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/patrickkoss/grpc-gateway-example/internal/adapter/api/domain/proto"
"google.golang.org/grpc/status"
)
func CustomHTTPError(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
// Convert the error to a customError
s := status.Convert(err)
// 2xx requests are fine
if s.Code() <= 300 {
runtime.DefaultHTTPErrorHandler(ctx, mux, marshaler, w, r, err)
return
}
if 200 > s.Code() && s.Code() > 505 {
runtime.DefaultHTTPErrorHandler(ctx, mux, marshaler, w, r, err)
return
}
errorMessage := proto.ErrorMessage{
Message: s.Message(),
Error: s.Message(),
}
for _, d := range s.Details() {
errorResponse, ok := d.(*proto.ErrorMessage)
if ok {
errorMessage.Error = errorResponse.Error
}
}
w.WriteHeader(int(s.Code()))
w.Header().Set("Content-Type", "application/json")
// Write the error details to the response body.
body, _ := marshaler.Marshal(proto.ErrorMessage{
Message: errorMessage.Message,
Error: errorMessage.Error,
})
_, _ = w.Write(body)
}