-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathresponserror.go
More file actions
68 lines (54 loc) · 1.36 KB
/
responserror.go
File metadata and controls
68 lines (54 loc) · 1.36 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
package httperror
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
)
type Responder interface {
Response() (int, codersdk.Response)
}
func IsResponder(err error) (Responder, bool) {
var responseErr Responder
if errors.As(err, &responseErr) {
return responseErr, true
}
return nil, false
}
func NewResponseError(status int, resp codersdk.Response) error {
return &responseError{
status: status,
response: resp,
}
}
func WriteResponseError(ctx context.Context, rw http.ResponseWriter, err error) {
if responseErr, ok := IsResponder(err); ok {
code, resp := responseErr.Response()
httpapi.Write(ctx, rw, code, resp)
return
}
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal server error",
Detail: err.Error(),
})
}
type responseError struct {
status int
response codersdk.Response
}
var (
_ error = (*responseError)(nil)
_ Responder = (*responseError)(nil)
)
func (e *responseError) Error() string {
return fmt.Sprintf("%s: %s", e.response.Message, e.response.Detail)
}
func (e *responseError) Status() int {
return e.status
}
func (e *responseError) Response() (int, codersdk.Response) {
return e.status, e.response
}
var ErrResourceNotFound = NewResponseError(http.StatusNotFound, httpapi.ResourceNotFoundResponse)