-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
72 lines (61 loc) · 1.59 KB
/
service.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package response
import (
"encoding/json"
"net/http"
)
var knownServiceErrors = map[string]bool{
"ValidationError": true,
"InternalError": true,
"NotFoundError": true,
"ConditionError": true,
"PermissionError": true,
}
type serviceError struct {
Code int32 `json:"code"`
ServiceName string `json:"service_name"`
Message string `json:"message"`
Destination string `json:"destination"`
Kind string `json:"kind"`
SublevelError interface{} `json:"details"`
}
func serviceErrorFromString(s string) (*serviceError, error) {
var e serviceError
if err := json.Unmarshal([]byte(s), &e); err != nil {
return nil, err
}
return &e, nil
}
func (s *serviceError) IsKnownError() bool {
_, ok := knownServiceErrors[s.Kind]
return ok
}
func (s *serviceError) ResponseCode() int {
switch s.Kind {
case "ValidationError":
return http.StatusBadRequest
case "NotFoundError":
return http.StatusNotFound
case "ConditionError":
return http.StatusPreconditionFailed
case "PermissionError":
return http.StatusUnauthorized
}
return http.StatusInternalServerError
}
func (s *serviceError) ToResponseError() *responseError {
opt := &responseErrorOptions{
Code: int(s.Code),
Source: s.ServiceName,
Message: s.Message,
Destination: s.Destination,
}
if s.SublevelError != nil {
if s.Kind == "ValidationError" {
// Encode the error details into a json string
b, _ := json.Marshal(s.SublevelError)
err := string(b)[1 : len(b)-1]
opt.Fields = newValidationErrorFields(err)
}
}
return newResponseError(opt)
}