forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
59 lines (49 loc) · 1.34 KB
/
errors.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
package gserv
import (
"fmt"
"net/http"
"github.com/alpineiq/otk"
)
type HTTPError interface {
Status() int
Error() string
}
var (
ErrBadRequest = NewError(http.StatusBadRequest, "bad request")
ErrUnauthorized = NewError(http.StatusUnauthorized, "unauthorized")
ErrForbidden = NewError(http.StatusForbidden, "the gates of time are closed")
ErrNotFound = NewError(http.StatusNotFound, "not found")
ErrTeaPot = NewError(http.StatusTeapot, "I'm a teapot")
ErrInternal = NewError(http.StatusInternalServerError, "internal error")
ErrNotImpl = NewError(http.StatusNotImplemented, "not implemented")
)
type Error struct {
Caller *callerInfo `json:"caller,omitempty"`
Message string `json:"message,omitempty"`
Code int `json:"code,omitempty"`
}
type callerInfo struct {
Func string `json:"func,omitempty"`
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
}
func NewError(status int, msg any) HTTPError {
e := Error{
Code: status,
Message: fmt.Sprint(msg),
}
return e
}
func NewErrorWithCaller(status int, msg string, skip int) HTTPError {
e := Error{
Code: status,
Message: msg,
}
if skip > 0 {
var c callerInfo
c.Func, c.File, c.Line = otk.Caller(1+skip, true)
}
return e
}
func (e Error) Status() int { return e.Code }
func (e Error) Error() string { return e.Message }