-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
56 lines (46 loc) · 922 Bytes
/
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
package err
import (
"errors"
"github.com/gin-gonic/gin"
)
func Error(errM ...*ErrorMap) gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
lastError := c.Errors.Last()
if lastError == nil {
return
}
for _, err := range errM {
if err.matchError(lastError.Err) {
err.response(c)
}
}
}
}
type ErrorMap struct {
errors []error
statusCode int
response func(c *gin.Context)
}
func (e *ErrorMap) StatusCode(statusCode int) *ErrorMap {
e.statusCode = statusCode
e.response = func(c *gin.Context) {
c.Status(statusCode)
}
return e
}
func (e *ErrorMap) Response(response func(c *gin.Context)) *ErrorMap {
e.response = response
return e
}
func (e *ErrorMap) matchError(actual error) bool {
for _, expected := range e.errors {
if errors.Is(actual, expected) {
return true
}
}
return false
}
func NewErrMap(err ...error) *ErrorMap {
return &ErrorMap{errors: err}
}