-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
44 lines (35 loc) · 840 Bytes
/
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
package gocardless
import (
"encoding/json"
"fmt"
"net/http"
)
type Error struct {
Summary string `json:"summary"`
Detail string `json:"detail"`
StatusCode int `json:"status_code"`
Type string `json:"type"`
}
func NewError(errResponse *http.Response) error {
var newErr Error
err := json.NewDecoder(errResponse.Body).Decode(&newErr)
if err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
if newErr.Summary == "" {
newErr.Summary = errResponse.Status
}
if newErr.Detail == "" {
newErr.Detail = errResponse.Status
}
if newErr.StatusCode == 0 {
newErr.StatusCode = errResponse.StatusCode
}
return &newErr
}
func (e *Error) Error() string {
return fmt.Sprintf("%d - %s: %s", e.StatusCode, e.Summary, e.Detail)
}
func ExtractError(err error) *Error {
return err.(*Error)
}