-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
120 lines (107 loc) · 2.57 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
115
116
117
118
119
120
package vcago
import (
"encoding/json"
"fmt"
"net/http"
"runtime"
"strings"
"time"
"go.mongodb.org/mongo-driver/mongo"
)
type Error struct {
ID string `json:"id"`
Time string `json:"time"`
Level string `json:"level"`
File string `json:"file"`
Line int `json:"line"`
Message string `json:"message"`
Err error `json:"-"`
Model string `json:"model,omitempty"`
Type string `json:"type"`
}
var LogLevel = Settings.String("LOG_LEVEL", "w", "DEBUG")
func (i *Error) Log() string {
err, _ := json.Marshal(i)
return string(err)
}
func (i *Error) Error() string {
return i.Err.Error()
}
func NewError(err error, lvl string, t string) *Error {
pc := make([]uintptr, 10)
runtime.Callers(3, pc)
f := runtime.FuncForPC(pc[0])
_, line := f.FileLine(pc[0])
file := runtime.FuncForPC(pc[0]).Name()
return &Error{
Time: time.Now().String(),
Level: lvl,
File: file,
Line: line,
Message: err.Error(),
Err: err,
Type: t,
}
}
func (i *Error) AddModel(model string) *Error {
i.Model = model
return i
}
func (i *Error) Print(id string) {
i.ID = id
if LogLevel == "DEBUG" {
fmt.Println(i.Log())
} else if LogLevel == "ERROR" {
if i.Level == "ERROR" {
fmt.Println(i.Log())
}
}
}
// MongoErrorResponseHandler handles the response for the MongoError type.
func (i *Error) Response() (int, interface{}) {
switch i.Type {
case "mongo":
return i.MongoResponse()
case "bind":
return i.BindResponse()
case "validation":
return i.ValidationResponse()
default:
return NewInternalServerError(i.Model).Response()
}
}
func (i *Error) MongoResponse() (int, interface{}) {
if strings.Contains(i.Message, "duplicate key error") {
temp := strings.Split(i.Message, "key: {")
temp = strings.Split(temp[1], "}")
response := &Response{
Status: http.StatusConflict,
Type: "error",
Message: "duplicate key error: " + temp[0],
Model: i.Model,
}
return response.Response()
}
switch i.Err {
case mongo.ErrNoDocuments:
response := &Response{
Status: http.StatusNotFound,
Type: "error",
Message: "docmument not found",
Model: i.Model,
}
return response.Response()
default:
return NewInternalServerError(i.Model).Response()
}
}
func (i *Error) BindResponse() (int, interface{}) {
response := new(ValidationError)
response.Bind(i.Err)
return NewBadRequest(i.Model, "bind error", response).Response()
}
func (i *Error) ValidationResponse() (int, interface{}) {
response := new(ValidationError)
response.Valid(i.Err)
return NewBadRequest(i.Model, "validation error", response).Response()
}