-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
84 lines (71 loc) · 2.37 KB
/
errors.go
File metadata and controls
84 lines (71 loc) · 2.37 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
72
73
74
75
76
77
78
79
80
81
82
83
84
package api
import (
"errors"
"fmt"
"net/http"
)
// Sentinel errors for request binding.
var (
ErrBindPath = errors.New("bind path")
ErrBindQuery = errors.New("bind query")
ErrBindHeader = errors.New("bind header")
ErrBindCookie = errors.New("bind cookie")
ErrBindBody = errors.New("bind body")
ErrBindForm = errors.New("bind form")
)
// StatusCoder is implemented by errors or responses that carry an HTTP status code.
type StatusCoder interface {
StatusCode() int
}
// ProblemDetail is an RFC 9457 problem details response.
//
//nolint:errname // RFC 9457 standard name
type ProblemDetail struct {
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Errors []ValidationError `json:"errors,omitempty"`
}
// Error returns the detail message (or title if detail is empty).
func (p *ProblemDetail) Error() string {
if p.Detail != "" {
return p.Detail
}
return p.Title
}
// StatusCode returns the HTTP status code.
func (p *ProblemDetail) StatusCode() int { return p.Status }
// ValidationError describes a single field validation failure.
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Value any `json:"value,omitempty"`
}
// HTTPError is an error with an HTTP status code.
type HTTPError struct {
Status int `json:"status"`
Message string `json:"message"`
}
// Error returns the error message.
func (e *HTTPError) Error() string { return e.Message }
// StatusCode returns the HTTP status code.
func (e *HTTPError) StatusCode() int { return e.Status }
// Error returns an error with the given HTTP status code and message.
func Error(status int, message string) error {
return &HTTPError{Status: status, Message: message}
}
// Errorf returns a formatted error with the given HTTP status code.
func Errorf(status int, format string, args ...any) error {
return &HTTPError{Status: status, Message: fmt.Sprintf(format, args...)}
}
// ErrorStatus extracts the HTTP status code from an error. Returns
// http.StatusInternalServerError if the error does not implement StatusCoder.
func ErrorStatus(err error) int {
var sc StatusCoder
if errors.As(err, &sc) {
return sc.StatusCode()
}
return http.StatusInternalServerError
}