-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy patherror.go
92 lines (77 loc) · 2.5 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package meilisearch
import (
"fmt"
"strings"
)
type ErrCode int
const (
ErrCodeUnknown ErrCode = 0
ErrCodeMarshalRequest ErrCode = iota + 1
ErrCodeRequestCreation
ErrCodeRequestExecution
ErrCodeResponseStatusCode
ErrCodeResponseReadBody
ErrCodeResponseUnmarshalBody
)
const (
rawStringCtx = `"ctx: Endpoint "${method} ${endpoint}" Function "${function}" Api "${apiName}"`
rawStringMarshalRequest = `unable to marshal body from request ${request}`
rawStringRequestCreation = `unable to create new request`
rawStringRequestExecution = `unable to execute request`
rawStringResponseStatusCode = `unaccepted status code found: ${statusCode} expected: ${statusCodeExpected}, message from api: '${RawMessage}'`
rawStringResponseReadBody = `unable to read body from response ${response}`
rawStringResponseUnmarshalBody = `unable to unmarshal body from response ${response}`
)
func (e ErrCode) rawMessage() string {
switch e {
case ErrCodeMarshalRequest:
return rawStringMarshalRequest + " " + rawStringCtx
case ErrCodeRequestCreation:
return rawStringRequestCreation + " " + rawStringCtx
case ErrCodeRequestExecution:
return rawStringRequestExecution + " " + rawStringCtx
case ErrCodeResponseStatusCode:
return rawStringResponseStatusCode + " " + rawStringCtx
case ErrCodeResponseReadBody:
return rawStringResponseReadBody + " " + rawStringCtx
case ErrCodeResponseUnmarshalBody:
return rawStringResponseUnmarshalBody + " " + rawStringCtx
default:
return "Unknown error " + rawStringCtx
}
}
type apiMessage struct {
Message string `json:"message"`
}
type Error struct {
Endpoint string
Method string
Function string
APIName string
RequestToString string
ResponseToString string
MeilisearchMessage string
StatusCode int
StatusCodeExpected []int
RawMessage string
ErrCode ErrCode
}
func (e Error) Error() string {
return namedSprintf(e.RawMessage, map[string]interface{}{
"endpoint": e.Endpoint,
"method": e.Method,
"function": e.Function,
"apiName": e.APIName,
"request": e.RequestToString,
"response": e.ResponseToString,
"meilisearchMessage": e.MeilisearchMessage,
"statusCodeExpected": e.StatusCodeExpected,
"statusCode": e.StatusCode,
})
}
func namedSprintf(format string, params map[string]interface{}) string {
for key, val := range params {
format = strings.ReplaceAll(format, "${"+key+"}s", fmt.Sprintf("%s", val))
}
return format
}