-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
75 lines (64 loc) · 1.89 KB
/
errors.go
File metadata and controls
75 lines (64 loc) · 1.89 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
package lnbot
import (
"encoding/json"
"fmt"
"net/http"
)
// APIError represents an error response from the LnBot API.
type APIError struct {
StatusCode int
Message string
Body string
}
func (e *APIError) Error() string {
return fmt.Sprintf("lnbot: %s (status %d)", e.Message, e.StatusCode)
}
// BadRequestError is returned for 400 responses.
type BadRequestError struct{ *APIError }
// UnauthorizedError is returned for 401 responses.
type UnauthorizedError struct{ *APIError }
// ForbiddenError is returned for 403 responses.
type ForbiddenError struct{ *APIError }
// NotFoundError is returned for 404 responses.
type NotFoundError struct{ *APIError }
// ConflictError is returned for 409 responses.
type ConflictError struct{ *APIError }
func (e *BadRequestError) Unwrap() error { return e.APIError }
func (e *UnauthorizedError) Unwrap() error { return e.APIError }
func (e *ForbiddenError) Unwrap() error { return e.APIError }
func (e *NotFoundError) Unwrap() error { return e.APIError }
func (e *ConflictError) Unwrap() error { return e.APIError }
func parseAPIError(statusCode int, body []byte) error {
msg := parseErrorMessage(body)
if msg == "" {
msg = http.StatusText(statusCode)
}
base := &APIError{StatusCode: statusCode, Message: msg, Body: string(body)}
switch statusCode {
case http.StatusBadRequest:
return &BadRequestError{base}
case http.StatusUnauthorized:
return &UnauthorizedError{base}
case http.StatusForbidden:
return &ForbiddenError{base}
case http.StatusNotFound:
return &NotFoundError{base}
case http.StatusConflict:
return &ConflictError{base}
default:
return base
}
}
func parseErrorMessage(body []byte) string {
var parsed struct {
Message string `json:"message"`
Error string `json:"error"`
}
if json.Unmarshal(body, &parsed) != nil {
return ""
}
if parsed.Message != "" {
return parsed.Message
}
return parsed.Error
}