Repository navigation
Expand file tree
/
Copy patherrors.go
More file actions
227 lines (201 loc) · 7.55 KB
/
Copy patherrors.go
File metadata and controls
227 lines (201 loc) · 7.55 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package deepl
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
)
// maxErrorMessage bounds the API error text kept in an [Error], limiting leakage
// of user text or handles into error values.
const maxErrorMessage = 200
// Kind sentinels. A [*Error] matches at most one of them with [errors.Is].
var (
// ErrAuthorization matches HTTP 401 and 403: the auth key is invalid or not
// authorized for the request.
ErrAuthorization = errors.New("deepl: authorization failed")
// ErrNotFound matches HTTP 404, and a glossary entries response without
// the requested dictionary.
ErrNotFound = errors.New("deepl: not found")
// ErrTooManyRequests matches HTTP 429 after all retries.
ErrTooManyRequests = errors.New("deepl: too many requests")
// ErrQuotaExceeded matches HTTP 456: the character or document quota is used up.
ErrQuotaExceeded = errors.New("deepl: quota exceeded")
// ErrConnection matches a failure without an HTTP response: DNS, connect,
// timeout, reset, unreachable host or network, TLS, or a proxy error answer.
ErrConnection = errors.New("deepl: connection failed")
// ErrDocumentNotReady matches HTTP 503 on a document download after all
// retries: the translation is not done yet.
ErrDocumentNotReady = errors.New("deepl: document not ready")
)
// Error is any failure the DeepL API or the connection to it produced, including
// a success response that could not be parsed. Match its kind with [errors.Is]
// against the Err* sentinels and read its fields with [errors.As].
type Error struct {
// Message is the API's error message (truncated), or a description of the
// connection or parsing failure.
Message string
// HTTPStatusCode is the status of the failed response, or 0 when no response
// arrived.
HTTPStatusCode int
// ShouldRetry reports whether repeating the call could succeed.
ShouldRetry bool
kind error
err error
}
func (e *Error) Error() string {
prefix := "deepl: error"
if e.kind != nil {
prefix = e.kind.Error()
}
msg := prefix
if e.Message != "" {
msg += ": " + e.Message
}
if e.HTTPStatusCode != 0 {
msg += " (HTTP " + strconv.Itoa(e.HTTPStatusCode) + ")"
}
return msg
}
// Is reports whether target is the error's kind sentinel.
func (e *Error) Is(target error) bool { return e.kind != nil && e.kind == target }
// Unwrap returns the underlying cause, if any (for example a transport error).
func (e *Error) Unwrap() error { return e.err }
// ArgumentError is an invalid argument or client option, returned before any
// request is sent. It is not an [*Error].
type ArgumentError struct {
Message string
}
func (e *ArgumentError) Error() string { return "deepl: invalid argument: " + e.Message }
func newArgumentError(msg string) *ArgumentError { return &ArgumentError{Message: msg} }
// DocumentTranslationError is any failure of [Client.TranslateDocument]. Handle
// is set once the upload succeeded, so the caller can wait for and download the
// (already billed) translation without uploading again. HTTPStatusCode and
// ShouldRetry are copied from an [*Error] cause; [errors.Is] and [errors.As]
// reach the cause through Unwrap.
type DocumentTranslationError struct {
// Handle identifies the uploaded document, or is nil if the failure came
// before the upload succeeded.
Handle *DocumentHandle
// Message describes the failure.
Message string
// HTTPStatusCode is the cause's status, or 0.
HTTPStatusCode int
// ShouldRetry is the cause's retry flag, or false.
ShouldRetry bool
err error
}
func (e *DocumentTranslationError) Error() string {
return "deepl: document translation failed: " + e.Message
}
// Unwrap returns the cause.
func (e *DocumentTranslationError) Unwrap() error { return e.err }
func newDocumentTranslationError(handle *DocumentHandle, cause error) *DocumentTranslationError {
// The cause's own "deepl: " prefix would repeat the one of Error().
msg := strings.TrimPrefix(strings.TrimPrefix(cause.Error(), "deepl: "), "error: ")
e := &DocumentTranslationError{Handle: handle, Message: msg, err: cause}
var de *Error
if errors.As(cause, &de) {
e.HTTPStatusCode = de.HTTPStatusCode
e.ShouldRetry = de.ShouldRetry
}
return e
}
// TranslationMemoryJobError is any failure of
// [Client.ImportTranslationMemoryFromFilepath] and
// [Client.ExportTranslationMemoryToFilepath]. JobID is set once the job was
// created and Job once its status was fetched, so the caller can resume with
// [Client.WaitUntilTranslationMemoryJobDone] instead of starting over.
// HTTPStatusCode and ShouldRetry are copied from an [*Error] cause; [errors.Is]
// and [errors.As] reach the cause through Unwrap.
type TranslationMemoryJobError struct {
// JobID identifies the job, or is "" if the failure came before it was
// created.
JobID string
// Job is the last status fetched, or nil before the first status request.
Job *TranslationMemoryJob
// Message describes the failure.
Message string
// HTTPStatusCode is the cause's status, or 0.
HTTPStatusCode int
// ShouldRetry is the cause's retry flag, or false.
ShouldRetry bool
err error
}
func (e *TranslationMemoryJobError) Error() string {
return "deepl: translation memory job failed: " + e.Message
}
// Unwrap returns the cause.
func (e *TranslationMemoryJobError) Unwrap() error { return e.err }
func newTranslationMemoryJobError(jobID string, job *TranslationMemoryJob, cause error) *TranslationMemoryJobError {
msg := strings.TrimPrefix(strings.TrimPrefix(cause.Error(), "deepl: "), "error: ")
e := &TranslationMemoryJobError{JobID: jobID, Job: job, Message: msg, err: cause}
var de *Error
if errors.As(cause, &de) {
e.HTTPStatusCode = de.HTTPStatusCode
e.ShouldRetry = de.ShouldRetry
}
return e
}
// statusError maps a non-success HTTP status to an [*Error] (B7). shouldRetry is
// decided by the caller, since creates and other requests differ (B4).
func statusError(status int, body []byte, shouldRetry bool) *Error {
var kind error
switch status {
case http.StatusUnauthorized, http.StatusForbidden:
kind = ErrAuthorization
case http.StatusNotFound:
kind = ErrNotFound
case http.StatusTooManyRequests:
kind = ErrTooManyRequests
case 456:
kind = ErrQuotaExceeded
}
return &Error{
Message: errorMessage(status, body),
HTTPStatusCode: status,
ShouldRetry: shouldRetry,
kind: kind,
}
}
// errorMessage extracts the API's message and detail from a JSON error body,
// falling back to the raw body, then to the status text.
func errorMessage(status int, body []byte) string {
var parsed struct {
Message *string `json:"message"`
Detail *string `json:"detail"`
}
var msg string
if err := json.Unmarshal(body, &parsed); err == nil {
var parts []string
if parsed.Message != nil && *parsed.Message != "" {
parts = append(parts, *parsed.Message)
}
if parsed.Detail != nil && *parsed.Detail != "" {
parts = append(parts, *parsed.Detail)
}
msg = strings.Join(parts, ": ")
} else {
msg = strings.TrimSpace(string(body))
}
if msg == "" {
msg = http.StatusText(status)
}
return truncateRunes(msg, maxErrorMessage)
}
func connectionError(msg string, shouldRetry bool, cause error) *Error {
return &Error{Message: msg, ShouldRetry: shouldRetry, kind: ErrConnection, err: cause}
}
// decodeError is a success response whose body could not be parsed (B8).
func decodeError(status int, msg string) *Error {
return &Error{Message: "failed to decode API response: " + msg, HTTPStatusCode: status}
}
// truncateRunes returns at most n runes of s (rune-safe, so it never splits a
// multi-byte character).
func truncateRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n])
}