/
errors.go
90 lines (81 loc) Β· 1.6 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package apis
import (
"fmt"
"net/http"
"github.com/sirupsen/logrus"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type Err struct {
Message string `json:"message"`
Code string `json:"code,omitempty"`
Status int `json:"status"`
Data interface{} `json:"data,omitempty"`
Reason string `json:"reason,omitempty"`
Cause error `json:"-"`
}
func (e Err) Error() string {
return e.Message
}
func FromError(err interface{}) *Err {
if err == nil {
return nil
}
var e *Err
switch v := err.(type) {
case Err:
e = &v
case *Err:
e = v
case error:
e = &Err{
Message: v.Error(),
Status: http.StatusInternalServerError,
Cause: v,
}
case string:
e = &Err{
Message: v,
Status: http.StatusInternalServerError,
Cause: errors.New(v),
}
default:
e = &Err{
Message: fmt.Sprint(err),
Status: http.StatusInternalServerError,
}
}
if e.Message == "" {
e.Message = http.StatusText(e.Status)
}
return e
}
func throwErrorStatus(err error, s int, f string, args ...interface{}) {
if err == nil {
return
}
panic(Err{
Status: s,
Message: fmt.Sprintf(f, args...),
Reason: err.Error(),
Cause: err,
})
}
func throwError(err error, fmt string, args ...interface{}) {
if err == nil {
return
}
throwErrorStatus(err, detectStatusCode(err), fmt, args...)
}
func swallowError(err error, fmt string, args ...interface{}) {
if err == nil {
return
}
logrus.WithError(err).Warnf(fmt, args...)
}
func detectStatusCode(err error) int {
if err == gorm.ErrRecordNotFound {
return http.StatusNotFound
}
return http.StatusInternalServerError
}