-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
109 lines (91 loc) · 2.44 KB
/
Copy patherrors.go
File metadata and controls
109 lines (91 loc) · 2.44 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package mysa
import (
"errors"
"fmt"
"io"
"net/http"
)
// Sentinel errors for type checking with errors.Is().
var (
ErrNotAuthenticated = errors.New("not authenticated")
ErrDeviceNotFound = errors.New("device not found")
)
// UnauthenticatedError indicates authentication is required.
type UnauthenticatedError struct {
Message string
Cause error
}
func (e *UnauthenticatedError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("%s: %v", e.Message, e.Cause)
}
return e.Message
}
func (e *UnauthenticatedError) Unwrap() error {
return e.Cause
}
func (e *UnauthenticatedError) Is(target error) bool {
return target == ErrNotAuthenticated
}
// MysaApiError represents an API request failure.
type MysaApiError struct {
StatusCode int
Status string
URL string
Body string
}
func (e *MysaApiError) Error() string {
if e.Body != "" {
return fmt.Sprintf("Mysa API error: %s returned %d (%s): %s", e.URL, e.StatusCode, e.Status, e.Body)
}
return fmt.Sprintf("Mysa API error: %s returned %d (%s)", e.URL, e.StatusCode, e.Status)
}
// NewMysaApiError creates an error from an HTTP response.
func NewMysaApiError(resp *http.Response) *MysaApiError {
body, _ := io.ReadAll(resp.Body)
return &MysaApiError{
StatusCode: resp.StatusCode,
Status: resp.Status,
URL: resp.Request.URL.String(),
Body: string(body),
}
}
// IsNotFound returns true if the error is a 404.
func (e *MysaApiError) IsNotFound() bool {
return e.StatusCode == http.StatusNotFound
}
// IsUnauthorized returns true if the error is a 401.
func (e *MysaApiError) IsUnauthorized() bool {
return e.StatusCode == http.StatusUnauthorized
}
// MqttPublishError represents a failed MQTT publish.
type MqttPublishError struct {
Topic string
Attempts int
Cause error
}
func (e *MqttPublishError) Error() string {
return fmt.Sprintf("MQTT publish to %s failed after %d attempts: %v",
e.Topic, e.Attempts, e.Cause)
}
func (e *MqttPublishError) Unwrap() error {
return e.Cause
}
// DeviceError represents a device-specific error.
type DeviceError struct {
DeviceId string
Message string
Cause error
}
func (e *DeviceError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("device %s: %s: %v", e.DeviceId, e.Message, e.Cause)
}
return fmt.Sprintf("device %s: %s", e.DeviceId, e.Message)
}
func (e *DeviceError) Unwrap() error {
return e.Cause
}
func (e *DeviceError) Is(target error) bool {
return target == ErrDeviceNotFound
}