-
Notifications
You must be signed in to change notification settings - Fork 1
/
error.go
54 lines (42 loc) · 1.08 KB
/
error.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
package httpx
import (
"context"
"encoding/json"
"net/http"
"github.com/pkg/errors"
"github.com/remind101/pkg/reporter"
)
func Error(ctx context.Context, err error, rw http.ResponseWriter, r *http.Request) {
reporter.Report(ctx, err)
EncodeError(err, rw)
}
type temporaryError interface {
Temporary() bool // Is the error temporary?
}
type timeoutError interface {
Timeout() bool // Is the error a timeout?
}
type statusCoder interface {
StatusCode() int
}
func EncodeError(err error, rw http.ResponseWriter) {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(ErrorStatusCode(err))
errorResp := map[string]string{
"error": err.Error(),
}
json.NewEncoder(rw).Encode(errorResp)
}
func ErrorStatusCode(err error) int {
rootErr := errors.Cause(err)
if e, ok := rootErr.(statusCoder); ok {
return e.StatusCode()
}
if e, ok := rootErr.(temporaryError); ok && e.Temporary() {
return http.StatusServiceUnavailable
}
if e, ok := rootErr.(timeoutError); ok && e.Timeout() {
return http.StatusServiceUnavailable
}
return http.StatusInternalServerError
}