-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patherror.go
114 lines (101 loc) · 2.44 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package cosy
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/uozi-tech/cosy/logger"
"github.com/uozi-tech/cosy/settings"
"go.uber.org/zap"
"gorm.io/gorm"
"net/http"
"strings"
)
type ErrorScope struct {
scope string
}
func NewErrorScope(scope string) *ErrorScope {
return &ErrorScope{scope}
}
// New create a new error with scope
func (s *ErrorScope) New(code int32, message string) error {
return &Error{
Scope: s.scope,
Code: code,
Message: message,
}
}
// NewWithParams create a new error with scope and params
func (s *ErrorScope) NewWithParams(code int32, message string, params ...string) error {
return &Error{
Scope: s.scope,
Code: code,
Message: message,
Params: params,
}
}
type Error struct {
Scope string `json:"scope,omitempty"`
Code int32 `json:"code"`
Message string `json:"message"`
Params []string `json:"params,omitempty"`
}
func (e *Error) Error() string {
if len(e.Params) == 0 {
return e.Message
}
msg := e.Message
for index, param := range e.Params {
msg = strings.Replace(msg, fmt.Sprintf("{%d}", index), param, 1)
}
return msg
}
// NewError create a new error
func NewError(code int32, message string) error {
return &Error{
Code: code,
Message: message,
}
}
// NewErrorWithParams create a new error with params
func NewErrorWithParams(code int32, message string, params ...string) error {
return &Error{
Code: code,
Message: message,
Params: params,
}
}
// errorResp error response
func errorResp(c *gin.Context, err error) {
var cErr *Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
c.JSON(http.StatusNotFound, &Error{
Code: http.StatusNotFound,
Message: gorm.ErrRecordNotFound.Error(),
})
case errors.As(err, &cErr):
c.JSON(http.StatusInternalServerError, cErr)
default:
if settings.ServerSettings.RunMode != gin.ReleaseMode {
c.JSON(http.StatusInternalServerError, &Error{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
return
}
c.JSON(http.StatusInternalServerError, &Error{
Code: http.StatusInternalServerError,
Message: "Server Error",
})
}
}
// errHandler error handler for internal use
func errHandler(c *gin.Context, err error) {
logger.GetLogger().WithOptions(zap.AddCallerSkip(1)).Errorln(err)
errorResp(c, err)
}
// ErrHandler error handler for external use
func ErrHandler(c *gin.Context, err error) {
logger.GetLogger().Errorln(err)
errorResp(c, err)
}