-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
76 lines (70 loc) · 1.9 KB
/
Copy patherrors.go
File metadata and controls
76 lines (70 loc) · 1.9 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
package cinc
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
// Sentinel errors for use with errors.Is.
var (
ErrNotFound = errors.New("cinc: not found")
ErrConflict = errors.New("cinc: conflict")
ErrForbidden = errors.New("cinc: forbidden")
ErrUnauthorized = errors.New("cinc: unauthorized")
)
// ErrorResponse describes a non-2xx response from the Chef server.
type ErrorResponse struct {
Method string // request method
Path string // request path
StatusCode int // HTTP status code
Messages []string // server-reported error messages
}
func (e *ErrorResponse) Error() string {
msg := strings.Join(e.Messages, "; ")
if msg == "" {
msg = "(no message)"
}
return fmt.Sprintf("cinc: %s %s: %d: %s", e.Method, e.Path, e.StatusCode, msg)
}
// Unwrap maps the status code to a sentinel error for errors.Is.
func (e *ErrorResponse) Unwrap() error {
switch e.StatusCode {
case 401:
return ErrUnauthorized
case 403:
return ErrForbidden
case 404:
return ErrNotFound
case 409:
return ErrConflict
default:
return nil
}
}
// newErrorResponse builds an *ErrorResponse, decoding the Chef error body.
func newErrorResponse(method, path string, code int, body []byte) *ErrorResponse {
er := &ErrorResponse{Method: method, Path: path, StatusCode: code}
var parsed struct {
Error json.RawMessage `json:"error"`
}
if json.Unmarshal(body, &parsed) == nil && parsed.Error != nil {
// "error" may be a []string or a bare string.
var list []string
if json.Unmarshal(parsed.Error, &list) == nil {
er.Messages = list
} else {
var s string
if json.Unmarshal(parsed.Error, &s) == nil {
er.Messages = []string{s}
}
}
}
if len(er.Messages) == 0 && len(body) > 0 {
er.Messages = []string{strings.TrimSpace(string(body))}
}
if code == 401 {
er.Messages = append(er.Messages,
"(check the client key and that the local clock is in sync)")
}
return er
}