-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest_errors.go
92 lines (79 loc) · 1.85 KB
/
rest_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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package rest_errors
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
type RestErr interface {
Message() string
Status() int
Error() string
Causes() []interface{}
}
type restErr struct {
ErrMessage string `json:"message"`
ErrStatus int `json:"status"`
ErrError string `json:"error"`
ErrCauses []interface{} `json:"causes"`
}
func (e restErr) Error() string {
return fmt.Sprintf("message: %s - status: %d - error: %s - causes: %v",
e.ErrMessage, e.ErrStatus, e.ErrError, e.ErrCauses)
}
func (e restErr) Message() string {
return e.ErrMessage
}
func (e restErr) Status() int {
return e.ErrStatus
}
func (e restErr) Causes() []interface{} {
return e.ErrCauses
}
func NewRestError(message string, status int, err string, causes []interface{}) RestErr {
return restErr{
ErrMessage: message,
ErrStatus: status,
ErrError: err,
ErrCauses: causes,
}
}
func NewRestErrorFromBytes(bytes []byte) (RestErr, error) {
var apiErr restErr
if err := json.Unmarshal(bytes, &apiErr); err != nil {
return nil, errors.New("invalid json")
}
return apiErr, nil
}
func NewBadRequestError(message string) RestErr {
return restErr{
ErrMessage: message,
ErrStatus: http.StatusBadRequest,
ErrError: "bad_request",
}
}
func NewNotFoundError(message string) RestErr {
return restErr{
ErrMessage: message,
ErrStatus: http.StatusNotFound,
ErrError: "not_found",
}
}
func NewUnauthorizedError(message string) RestErr {
return restErr{
ErrMessage: message,
ErrStatus: http.StatusUnauthorized,
ErrError: "unauthorized",
}
}
func NewInternalServerError(message string, err error) RestErr {
result := restErr{
ErrMessage: message,
ErrStatus: http.StatusInternalServerError,
ErrError: "internal_server_error",
}
if err != nil {
result.ErrCauses = append(result.ErrCauses, err.Error())
}
return result
}