-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy patherrors.go
More file actions
339 lines (301 loc) · 9.89 KB
/
Copy patherrors.go
File metadata and controls
339 lines (301 loc) · 9.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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package epo_ops
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"strings"
)
// AuthError represents an authentication error.
type AuthError struct {
StatusCode int
Message string
}
func (e *AuthError) Error() string {
if e.StatusCode > 0 {
return fmt.Sprintf("auth error (status %d): %s", e.StatusCode, e.Message)
}
return fmt.Sprintf("auth error: %s", e.Message)
}
// NotFoundError represents a 404 error (document doesn't exist).
type NotFoundError struct {
Resource string
Message string
}
func (e *NotFoundError) Error() string {
if e.Resource != "" {
return fmt.Sprintf("not found: %s (%s)", e.Resource, e.Message)
}
return fmt.Sprintf("not found: %s", e.Message)
}
// QuotaExceededError represents a fair use quota limit error.
type QuotaExceededError struct {
Message string
// RetryAfter is the raw Retry-After header value from the throttled
// response, when the server sent one; empty otherwise.
RetryAfter string
}
func (e *QuotaExceededError) Error() string {
return fmt.Sprintf("quota exceeded: %s", e.Message)
}
// ForbiddenError represents an HTTP 403 response that is not a quota or rate
// limit condition (e.g. the account lacks access to the requested resource).
type ForbiddenError struct {
StatusCode int
Message string
}
func (e *ForbiddenError) Error() string {
return fmt.Sprintf("forbidden (status %d): %s", e.StatusCode, e.Message)
}
// AmbiguousPatentError represents a situation where a patent number
// has multiple kind codes available (A1, B1, etc.) and the user must
// choose a specific one.
type AmbiguousPatentError struct {
Country string
Number string
KindCodes []string
Message string
}
func (e *AmbiguousPatentError) Error() string {
if len(e.KindCodes) > 0 {
return fmt.Sprintf("ambiguous patent %s%s, available kinds: %v - %s",
e.Country, e.Number, e.KindCodes, e.Message)
}
return fmt.Sprintf("ambiguous patent %s%s - %s", e.Country, e.Number, e.Message)
}
// ServiceUnavailableError represents a temporary service outage.
type ServiceUnavailableError struct {
StatusCode int
Message string
RetryAfter string // Optional Retry-After header value
}
func (e *ServiceUnavailableError) Error() string {
if e.RetryAfter != "" {
return fmt.Sprintf("service unavailable (status %d): %s, retry after: %s",
e.StatusCode, e.Message, e.RetryAfter)
}
return fmt.Sprintf("service unavailable (status %d): %s", e.StatusCode, e.Message)
}
// OPSError represents a structured error response from EPO OPS API.
// The EPO OPS API returns errors in XML format with a code, message, and optional moreInfo URL.
type OPSError struct {
HTTPStatus int // HTTP status code
Code string // EPO error code (e.g., "CLIENT.InvalidReference", "SERVER.EntityNotFound")
Message string // Human-readable error message
MoreInfo string // Optional URL with more information
}
func (e *OPSError) Error() string {
if e.MoreInfo != "" {
return fmt.Sprintf("[%d] %s: %s (see %s)", e.HTTPStatus, e.Code, e.Message, e.MoreInfo)
}
return fmt.Sprintf("[%d] %s: %s", e.HTTPStatus, e.Code, e.Message)
}
// XMLParseError represents an error during XML parsing.
// This error provides context about what failed during XML unmarshaling
// including the parser name, problematic element, and a sample of the XML.
type XMLParseError struct {
Parser string // e.g., "ParseFamily", "ParseLegal"
Element string // e.g., "family-member", "legal-event"
XMLSample string // First 200 chars of problematic XML
Cause error // Underlying error from xml.Unmarshal
}
func (e *XMLParseError) Error() string {
msg := fmt.Sprintf("XML parsing failed in %s", e.Parser)
if e.Element != "" {
msg += fmt.Sprintf(" (element: %s)", e.Element)
}
if e.Cause != nil {
msg += fmt.Sprintf(": %v", e.Cause)
}
if e.XMLSample != "" {
msg += fmt.Sprintf("\nXML sample: %s", e.XMLSample)
}
return msg
}
func (e *XMLParseError) Unwrap() error {
return e.Cause
}
// DataValidationError represents an error when parsed data is incomplete or invalid.
// This occurs when XML unmarshaling succeeds but the resulting data structure
// is missing required fields or contains invalid values.
type DataValidationError struct {
Parser string // e.g., "ParseFamily", "ParseLegal"
MissingField string // Name of the missing or invalid field
Message string // Description of what's wrong
}
func (e *DataValidationError) Error() string {
msg := fmt.Sprintf("data validation failed in %s", e.Parser)
if e.MissingField != "" {
msg += fmt.Sprintf(" (field: %s)", e.MissingField)
}
if e.Message != "" {
msg += fmt.Sprintf(": %s", e.Message)
}
return msg
}
// parseErrorXML parses EPO OPS error response XML into an OPSError struct.
// EPO error responses can have two formats:
//
// Format 1 (detailed error):
//
// <error>
// <code>CLIENT.InvalidReference</code>
// <message>Invalid patent number format</message>
// <moreInfo>http://...</moreInfo>
// </error>
//
// Format 2 (fault):
//
// <fault xmlns="http://ops.epo.org">
// <code>404</code>
// <message>Document not found</message>
// <description>No published document found...</description>
// </fault>
func parseErrorXML(body []byte, statusCode int) (*OPSError, error) {
// Try format 1: <error> with string codes
var errResp struct {
XMLName xml.Name `xml:"error"`
Code string `xml:"code"`
Message string `xml:"message"`
MoreInfo string `xml:"moreInfo"`
}
lastErr := xml.Unmarshal(body, &errResp)
if lastErr == nil && errResp.Code != "" {
return &OPSError{
HTTPStatus: statusCode,
Code: errResp.Code,
Message: errResp.Message,
MoreInfo: errResp.MoreInfo,
}, nil
}
// Try format 2: <fault> with numeric codes and description
var faultResp struct {
XMLName xml.Name `xml:"fault"`
Code string `xml:"code"`
Message string `xml:"message"`
Description string `xml:"description"`
}
if err := xml.Unmarshal(body, &faultResp); err == nil && faultResp.Code != "" {
// Use description as message if available, otherwise use message
message := faultResp.Message
if faultResp.Description != "" {
message = faultResp.Description
}
return &OPSError{
HTTPStatus: statusCode,
Code: "HTTP." + faultResp.Code, // Prefix numeric codes with "HTTP."
Message: message,
MoreInfo: "",
}, nil
} else if err != nil {
lastErr = err
}
// Could not parse as either known format. Surface a sample of the body so
// callers can diagnose unexpected responses.
return nil, &XMLParseError{
Parser: "parseErrorXML",
XMLSample: xmlSample(body),
Cause: lastErr,
}
}
// xmlSample returns a truncated, single-line sample of a response body suitable
// for inclusion in error messages.
func xmlSample(body []byte) string {
const maxLen = 200
sample := strings.TrimSpace(string(body))
if len(sample) > maxLen {
sample = sample[:maxLen] + "..."
}
return sample
}
// parseEPOJSONErrorBody decodes EPO's JSON error envelope. EPO returns some
// upstream backend errors as HTTP 200 with a JSON body preceded by one or
// more XML processing instructions, which would otherwise reach the XML
// parsers downstream. The body looks like:
//
// <?xml-stylesheet type='text/xsl' href='...'?>{"error":{"message":"...","details":{"original":{"code":404,"message":"..."}}}}
//
// It returns nil when the body does not match this shape. Common upstream
// codes are mapped to existing error types so callers can use the standard
// errors.Is / errors.As patterns.
func parseEPOJSONErrorBody(body []byte) error {
start := bytes.IndexByte(body, '{')
if start < 0 {
return nil
}
var payload struct {
Error struct {
Message string `json:"message"`
Code string `json:"code"`
Details struct {
Original struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"original"`
} `json:"details"`
} `json:"error"`
}
if err := json.Unmarshal(body[start:], &payload); err != nil {
return nil
}
message := payload.Error.Details.Original.Message
if message == "" {
message = payload.Error.Message
}
code := payload.Error.Details.Original.Code
if message == "" && code == 0 {
return nil
}
switch code {
case http.StatusNotFound:
return &NotFoundError{Message: message}
case http.StatusUnauthorized:
return &AuthError{StatusCode: code, Message: message}
case http.StatusForbidden:
// A bare 403 is a forbidden/access error, not a quota error - mirror the
// XML path so callers can treat 403 as non-retryable.
return &ForbiddenError{StatusCode: code, Message: message}
case http.StatusTooManyRequests:
return &QuotaExceededError{Message: message}
case http.StatusServiceUnavailable:
return &ServiceUnavailableError{StatusCode: code, Message: message}
}
statusCode := code
if statusCode == 0 {
statusCode = http.StatusOK
}
return &OPSError{
HTTPStatus: statusCode,
Code: fmt.Sprintf("HTTP.%d", statusCode),
Message: message,
}
}
// ConfigError represents a configuration error.
type ConfigError struct {
Message string
}
func (e *ConfigError) Error() string {
return fmt.Sprintf("config error: %s", e.Message)
}
// ValidationError represents an input validation error.
// This is returned when user-provided input doesn't match the expected format.
type ValidationError struct {
Field string // Field name that failed validation (e.g., "number", "format", "date")
Format string // Expected format (e.g., "docdb", "epodoc")
Value string // The invalid value provided
Message string // Human-readable error message
}
func (e *ValidationError) Error() string {
if e.Format != "" {
return fmt.Sprintf("validation error: %s (%s format): %s - got: %q", e.Field, e.Format, e.Message, e.Value)
}
return fmt.Sprintf("validation error: %s: %s - got: %q", e.Field, e.Message, e.Value)
}
// NotImplementedError represents a not-yet-implemented feature.
type NotImplementedError struct {
Message string
}
func (e *NotImplementedError) Error() string {
return fmt.Sprintf("not implemented: %s", e.Message)
}