-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
55 lines (50 loc) · 1.12 KB
/
errors.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
55
package couchserver
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/go-kivik/kivik/v4"
"github.com/go-kivik/kivikd/v4/internal"
)
func errorDescription(status int) string {
switch status {
case 401:
return "unauthorized"
case 400:
return "bad_request"
case 404:
return "not_found"
case 500:
return "internal_server_error" // TODO: Validate that this is normative
case 501:
return "not_implemented" // Non-standard
}
panic(fmt.Sprintf("unknown status %d", status))
}
type couchError struct {
Error string `json:"error"`
Reason string `json:"reason"`
}
// HandleError returns a CouchDB-formatted error. It does nothing if err is nil.
func (h *Handler) HandleError(w http.ResponseWriter, err error) {
if err == nil {
return
}
status := kivik.HTTPStatus(err)
w.WriteHeader(status)
var reason string
kerr := new(internal.Error)
if errors.As(err, &kerr) {
reason = kerr.Message
} else {
reason = err.Error()
}
wErr := json.NewEncoder(w).Encode(couchError{
Error: errorDescription(status),
Reason: reason,
})
if wErr != nil {
h.Logger.Printf("Failed to send send error: %s", wErr)
}
}