This repository has been archived by the owner on Feb 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
91 lines (81 loc) · 2 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
package raptor
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/si3nloong/raptor/validator"
"github.com/valyala/fasthttp"
)
type (
errorClaim struct {
Error struct {
Code string `json:"code" xml:"code"`
Message string `json:"message" xml:"message"`
Debug string `json:"debug,omitempty" xml:"debug,omitempty"`
Detail interface{} `json:"detail,omitempty" xml:"detail,omitempty"`
} `json:"error" xml:"error"`
}
)
// APIError :
type APIError struct {
Inner error
Code string
Message string
Detail interface{}
isDebug bool
}
// MarshalJSON :
func (e *APIError) MarshalJSON() (b []byte, err error) {
r := new(errorClaim)
r.Error.Code = e.Code
r.Error.Message = e.Message
if e.isDebug && e.Inner != nil {
r.Error.Debug = e.Inner.Error()
}
r.Error.Detail = e.Detail
b, err = json.Marshal(r)
return
}
func (e *APIError) Error() string {
blr := new(strings.Builder)
if e.Inner != nil {
blr.WriteString(fmt.Sprintf("debug=%s, ", e.Inner.Error()))
}
blr.WriteString(fmt.Sprintf("code=%s, message=%s", e.Code, e.Message))
if e.Detail != nil {
blr.WriteString(fmt.Sprintf(", detail=%v", e.Detail))
}
return blr.String()
}
// HTTPError :
type HTTPError struct {
StatusCode int
Message interface{}
Inner error
}
func (e *HTTPError) Error() string {
return fmt.Sprintf("code=%d, message=%v", e.StatusCode, e.Message)
}
// DefaultErrorHandler :
func DefaultErrorHandler(ctx *Context, err error) {
statusCode := fasthttp.StatusInternalServerError
if ctx.RequestCtx.Response.StatusCode() >= 400 {
statusCode = ctx.RequestCtx.Response.StatusCode()
}
switch ve := err.(type) {
case *APIError:
if ve.Code == "" {
ve.Code = strconv.Itoa(statusCode)
}
if ve.Message == "" {
ve.Message = http.StatusText(statusCode)
}
err = ctx.Response().compileResponse(ve, statusCode)
case *validator.ValidationError:
err = ctx.Response().compileResponse(ve, statusCode)
default:
err = ctx.Response().compileResponse(ve, statusCode)
}
}