-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors.go
More file actions
71 lines (61 loc) · 2.02 KB
/
Copy patherrors.go
File metadata and controls
71 lines (61 loc) · 2.02 KB
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
package gserv
import (
"fmt"
"net/http"
"go.oneofone.dev/otk"
)
// HTTPError is the interface for HTTP errors with a status code and message.
type HTTPError interface {
Status() int
Error() string
}
var (
// ErrBadRequest indicates a bad request (400).
ErrBadRequest = NewError(http.StatusBadRequest, "bad request")
// ErrUnauthorized indicates an unauthorized request (401).
ErrUnauthorized = NewError(http.StatusUnauthorized, "unauthorized")
// ErrForbidden indicates a forbidden request (403).
ErrForbidden = NewError(http.StatusForbidden, "the gates of time are closed")
// ErrNotFound indicates a resource not found (404).
ErrNotFound = NewError(http.StatusNotFound, "not found")
// ErrTeaPot is a fun 418 error.
ErrTeaPot = NewError(http.StatusTeapot, "I'm a teapot")
// ErrInternal indicates an internal server error (500).
ErrInternal = NewError(http.StatusInternalServerError, "internal error")
// ErrNotImpl indicates a not implemented error (501).
ErrNotImpl = NewError(http.StatusNotImplemented, "not implemented")
)
// Error is a standard HTTP error with an optional caller info.
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"`
}
// NewError creates a new HTTPError with the given status code and message.
func NewError(status int, msg any) HTTPError {
e := Error{
Code: status,
Message: fmt.Sprint(msg),
}
return e
}
// NewErrorWithCaller creates a new HTTPError with the given status code, message, and caller information.
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)
e.Caller = &c
}
return e
}
func (e Error) Status() int { return e.Code }
func (e Error) Error() string { return e.Message }