-
Notifications
You must be signed in to change notification settings - Fork 7
/
error.go
88 lines (81 loc) · 2.14 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package openproject
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"io"
"strings"
)
// Error message from OpenProject
type Error struct {
HTTPError error
ErrorMessages []string `json:"errorMessages"`
Errors map[string]string `json:"errors"`
}
// NewOpenProjectError creates a new OpenProject Error
func NewOpenProjectError(resp *Response, httpError error) error {
if resp == nil {
return errors.Wrap(httpError, "No response returned")
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, httpError.Error())
}
jerr := Error{HTTPError: httpError}
contentType := resp.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
err = json.Unmarshal(body, &jerr)
if err != nil {
httpError = errors.Wrap(errors.New("could not parse JSON"), httpError.Error())
return errors.Wrap(err, httpError.Error())
}
} else {
if httpError == nil {
return fmt.Errorf("got response status %s:%s", resp.Status, string(body))
}
return errors.Wrap(httpError, fmt.Sprintf("%s: %s", resp.Status, string(body)))
}
return &jerr
}
// Error is a short string representing the error
func (e *Error) Error() string {
if len(e.ErrorMessages) > 0 {
// return fmt.Sprintf("%v", e.HTTPError)
return fmt.Sprintf("%s: %v", e.ErrorMessages[0], e.HTTPError)
}
if len(e.Errors) > 0 {
for key, value := range e.Errors {
return fmt.Sprintf("%s - %s: %v", key, value, e.HTTPError)
}
}
return e.HTTPError.Error()
}
// LongError is a full representation of the error as a string
func (e *Error) LongError() string {
var msg bytes.Buffer
if e.HTTPError != nil {
msg.WriteString("Original:\n")
msg.WriteString(e.HTTPError.Error())
msg.WriteString("\n")
}
if len(e.ErrorMessages) > 0 {
msg.WriteString("Messages:\n")
for _, v := range e.ErrorMessages {
msg.WriteString(" - ")
msg.WriteString(v)
msg.WriteString("\n")
}
}
if len(e.Errors) > 0 {
for key, value := range e.Errors {
msg.WriteString(" - ")
msg.WriteString(key)
msg.WriteString(" - ")
msg.WriteString(value)
msg.WriteString("\n")
}
}
return msg.String()
}