-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
71 lines (58 loc) · 1.42 KB
/
errors.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
package ippanel
import (
"encoding/json"
"errors"
"fmt"
)
// ResponseCode api response code error type
type ResponseCode int
const (
ErrForbidden ResponseCode = 403
ErrNotFound ResponseCode = 404
ErrUnprocessableEntity ResponseCode = 422
ErrInternalServer ResponseCode = 500
)
// Error general service error
type Error struct {
Code ResponseCode
Message interface{}
}
// FieldErrs input field level errors
type FieldErrs map[string][]string
// Error implement error interface
func (e Error) Error() string {
switch e.Message.(type) {
case string:
return e.Message.(string)
case FieldErrs:
m, _ := json.Marshal(e.Message)
return string(m)
}
return fmt.Sprint(e.Code)
}
// fieldErrsRes field errors response
type fieldErrsRes struct {
Errors FieldErrs `json:"error"`
}
// defaultErrsRes default template for errors body
type defaultErrsRes struct {
Errors string `json:"error"`
}
// ParseErrors ...
func ParseErrors(res *BaseResponse) error {
var err error
e := Error{Code: res.Code}
messageFieldErrs := fieldErrsRes{}
if err = json.Unmarshal(res.Data, &messageFieldErrs); err == nil {
e.Message = messageFieldErrs.Errors
} else {
messageDefaultErrs := defaultErrsRes{}
if err = json.Unmarshal(res.Data, &messageDefaultErrs); err == nil {
e.Message = messageDefaultErrs.Errors
}
}
if err != nil {
return errors.New("cant marshal errors into standard template")
}
return e
}