-
Notifications
You must be signed in to change notification settings - Fork 25
/
error.go
76 lines (65 loc) · 2.07 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
package bot
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"runtime"
)
type Error struct {
Status int `json:"status"`
Code int `json:"code"`
Description string `json:"description"`
Extra interface{} `json:"extra,omitempty"`
trace string
}
func (sessionError Error) Error() string {
str, err := json.Marshal(sessionError)
if err != nil {
log.Panicln(err)
}
return string(str)
}
func BlazeServerError(ctx context.Context, err error) Error {
description := "Blaze server error."
return createError(ctx, http.StatusInternalServerError, 7000, description, err)
}
func ServerError(ctx context.Context, err error) Error {
description := http.StatusText(http.StatusInternalServerError)
return createError(ctx, http.StatusInternalServerError, http.StatusInternalServerError, description, err)
}
func BadDataError(ctx context.Context) Error {
description := "The request data has invalid field."
return createError(ctx, http.StatusAccepted, 10002, description, nil)
}
func AuthorizationError(ctx context.Context) Error {
description := "Unauthorized, maybe invalid token."
return createError(ctx, http.StatusAccepted, 401, description, nil)
}
func ForbiddenError(ctx context.Context) Error {
description := http.StatusText(http.StatusForbidden)
return createError(ctx, http.StatusAccepted, http.StatusForbidden, description, nil)
}
func NotFoundError(ctx context.Context) Error {
description := "The endpoint is not found."
return createError(ctx, http.StatusAccepted, http.StatusNotFound, description, nil)
}
func createError(ctx context.Context, status, code int, description string, err error) Error {
pc, file, line, _ := runtime.Caller(2)
_ = runtime.FuncForPC(pc).Name()
trace := fmt.Sprintf("[ERROR %d] %s\n%s:%d", code, description, file, line)
if err != nil {
if sessionError, ok := err.(Error); ok {
trace = trace + "\n" + sessionError.trace
} else {
trace = trace + "\n" + err.Error()
}
}
return Error{
Status: status,
Code: code,
Description: description,
trace: trace,
}
}