-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patherrors.go
54 lines (46 loc) · 1.04 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
package gotado
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
type apiErrors struct {
Errors []apiError `json:"errors"`
}
func (es *apiErrors) Error() string {
errs := make([]string, len(es.Errors))
for i, e := range es.Errors {
errs[i] = e.Error()
}
return strings.Join(errs, ", ")
}
type apiError struct {
Code string `json:"code"`
Title string `json:"title"`
}
func (e *apiError) Error() string {
return fmt.Sprintf("%s: %s", cases.Title(language.Und).String(e.Code), e.Title)
}
func isError(resp *http.Response) error {
if resp == nil {
return errors.New("response is nil")
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
var errs apiErrors
if err := json.NewDecoder(resp.Body).Decode(&errs); err != nil {
return fmt.Errorf("unable to decode API error: %w", err)
}
if len(errs.Errors) == 1 {
return &errs.Errors[0]
} else if len(errs.Errors) == 0 {
return fmt.Errorf("API returned empty error")
} else {
return &errs
}
}