-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
47 lines (40 loc) · 1.73 KB
/
Copy patherrors.go
File metadata and controls
47 lines (40 loc) · 1.73 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
package apihandler
import "fmt"
// StatusError is an error carrying an HTTP status code and a client-safe
// detail message. WriteProblem renders it as an RFC 9457 problem response
// using Status and Detail; internal information belongs in the wrapped Err,
// which is never exposed to the client.
type StatusError struct {
Status int // Status is the HTTP status code the error should produce.
Detail string // Detail is a human-readable explanation safe to show the client.
Err error // Err is the optional wrapped cause, for logs and errors.Is/As only.
}
// Error is the constructor for the common case:
//
// apihandler.Error(http.StatusNotFound, "no such user")
//
// It returns the concrete *StatusError so callers can read Status and
// Detail directly; the value is assignable to error wherever needed. Use a
// StatusError literal directly when a wrapped cause is needed.
func Error(status int, detail string) *StatusError {
return &StatusError{Status: status, Detail: detail}
}
// Error returns the status, detail, and wrapped cause, if any.
func (e *StatusError) Error() string {
if e.Err != nil {
return fmt.Sprintf("%d %s: %v", e.Status, e.Detail, e.Err)
}
return fmt.Sprintf("%d %s", e.Status, e.Detail)
}
// Unwrap returns the wrapped cause for errors.Is and errors.As traversal.
func (e *StatusError) Unwrap() error {
return e.Err
}
// HTTPStatus returns the HTTP status code. WriteProblem resolves status
// codes through the interface{ HTTPStatus() int } contract, so foreign
// error types implementing the same method participate without importing
// this package. A status outside the 400-599 range problem responses
// require is coerced to 500 by WriteProblem.
func (e *StatusError) HTTPStatus() int {
return e.Status
}