-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient_utils.go
More file actions
77 lines (69 loc) · 2.11 KB
/
client_utils.go
File metadata and controls
77 lines (69 loc) · 2.11 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
package threads
import (
"encoding/json"
"fmt"
"time"
)
// getUserID extracts user ID from token info
func (c *Client) getUserID() string {
c.mu.RLock()
defer c.mu.RUnlock()
if c.tokenInfo != nil && c.tokenInfo.UserID != "" {
return c.tokenInfo.UserID
}
return ""
}
// handleAPIError processes API error responses
func (c *Client) handleAPIError(resp *Response) error {
var apiErr struct {
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Code int `json:"code"`
IsTransient bool `json:"is_transient"`
ErrorSubcode int `json:"error_subcode"`
ErrorData struct {
Details string `json:"details"`
} `json:"error_data"`
} `json:"error"`
}
// Try to parse structured error response
if len(resp.Body) > 0 {
if err := json.Unmarshal(resp.Body, &apiErr); err == nil && apiErr.Error.Message != "" {
message := apiErr.Error.Message
details := apiErr.Error.ErrorData.Details
errorCode := apiErr.Error.Code
isTransient := apiErr.Error.IsTransient
if errorCode == 0 {
errorCode = resp.StatusCode
}
// Return appropriate error type based on status code
var resultErr error
switch resp.StatusCode {
case 401, 403:
resultErr = NewAuthenticationError(errorCode, message, details)
case 429:
var retryAfter time.Duration
if resp.RateLimit != nil {
retryAfter = resp.RateLimit.RetryAfter
}
resultErr = NewRateLimitError(errorCode, message, details, retryAfter)
case 400, 422:
resultErr = NewValidationError(errorCode, message, details, "")
default:
resultErr = NewAPIError(errorCode, message, details, resp.RequestID)
}
setErrorMetadata(resultErr, isTransient, resp.StatusCode, apiErr.Error.ErrorSubcode)
return resultErr
}
}
// Fallback to generic error
message := fmt.Sprintf("API request failed with status %d", resp.StatusCode)
details := string(resp.Body)
if len(details) > 500 {
details = details[:500] + "..."
}
fallbackErr := NewAPIError(resp.StatusCode, message, details, resp.RequestID)
setErrorMetadata(fallbackErr, false, resp.StatusCode, 0)
return fallbackErr
}