From 658937b178a120007be519f5c0ee1905c946764b Mon Sep 17 00:00:00 2001 From: Tim Walsh Date: Tue, 17 Nov 2026 23:50:38 -0700 Subject: [PATCH] fix(api): map ClickUp API errors to typed, user-friendly errors Client.handleError was a passthrough, so users saw raw SDK strings such as "GET https://api.clickup.com/api/v2/task/x: 401 Team not authorized OAUTH_027". It now converts the SDK's ErrorResponse, RateLimitError and AbuseRateLimitError into *errors.APIError, which carries a category sentinel (ErrNotAuthenticated, ErrPermissionDenied, ErrNotFound, ErrRateLimited, ErrServer, ErrInvalidInput), resource context parsed from the request path, and the HTTP status/ECODE/ClickUp message in a trailing parenthetical. The original SDK error stays in the unwrap chain. ClickUp answers 401 OAUTH_027 "Team not authorized" for IDs the token cannot see, including typos, so that case reads as not found rather than telling the user to log in again. internal/errors drops the never-called UserError and HandleHTTPError and the unused ErrConfigNotFound in favour of the single APIError type. Part of #27 Co-Authored-By: Claude Opus 5.5 --- internal/api/client.go | 11 -- internal/api/errors.go | 112 +++++++++++++++ internal/api/errors_test.go | 242 +++++++++++++++++++++++++++++++++ internal/errors/errors.go | 182 +++++++++++++++---------- internal/errors/errors_test.go | 149 ++++++++++---------- 5 files changed, 537 insertions(+), 159 deletions(-) create mode 100644 internal/api/errors.go create mode 100644 internal/api/errors_test.go diff --git a/internal/api/client.go b/internal/api/client.go index 5c87ee1..c57ca8d 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -225,17 +225,6 @@ func (c *Client) GetWorkspaceMembers(ctx context.Context, workspaceID string) ([ return users, nil } -// handleError converts API errors to user-friendly errors -func (c *Client) handleError(err error) error { - if err == nil { - return nil - } - - // TODO: Parse HTTP response codes and convert to appropriate errors - // For now, return the error as-is - return err -} - // TaskQueryOptions represents options for querying tasks type TaskQueryOptions struct { Page int diff --git a/internal/api/errors.go b/internal/api/errors.go new file mode 100644 index 0000000..f4d443b --- /dev/null +++ b/internal/api/errors.go @@ -0,0 +1,112 @@ +package api + +import ( + stderrors "errors" + "net/http" + "strconv" + "strings" + "time" + + "github.com/raksul/go-clickup/clickup" + "github.com/timimsms/cu/internal/errors" +) + +// resourceNames maps the first segment of a ClickUp API path to the noun +// used in error messages. ClickUp calls workspaces "teams" in its API. +var resourceNames = map[string]string{ + "task": "task", + "list": "list", + "folder": "folder", + "space": "space", + "team": "workspace", + "comment": "comment", + "view": "view", + "goal": "goal", +} + +// handleError converts SDK errors for failed ClickUp responses into typed, +// user-friendly *errors.APIError values. Network and context errors, and +// errors that are already typed, pass through unchanged. +func (c *Client) handleError(err error) error { + if err == nil { + return nil + } + + var typed *errors.APIError + if stderrors.As(err, &typed) { + return err + } + + var ( + resp *http.Response + status int + ecode, msg string + retryAfter time.Duration + ) + + var rateErr *clickup.RateLimitError + var abuseErr *clickup.AbuseRateLimitError + var respErr *clickup.ErrorResponse + switch { + case stderrors.As(err, &rateErr): + // The SDK also returns this without a request when it already knows + // the limit is exhausted, using a synthetic 403 response. + resp, status, msg = rateErr.Response, http.StatusTooManyRequests, rateErr.Message + if reset := rateErr.Rate.Reset.Time; !reset.IsZero() { + retryAfter = time.Until(reset) + } + case stderrors.As(err, &abuseErr): + resp, status, msg = abuseErr.Response, http.StatusTooManyRequests, abuseErr.Message + case stderrors.As(err, &respErr) && respErr.Response != nil: + resp, status = respErr.Response, respErr.Response.StatusCode + ecode, msg = respErr.ECode, respErr.Err + if msg == "" { + msg = respErr.Message + } + default: + return err + } + + apiErr := errors.NewAPIError(status, ecode, msg, err) + if resp != nil { + if resp.Request != nil && resp.Request.URL != nil { + apiErr.Resource, apiErr.ResourceID = c.resourceFromPath(resp.Request.URL.Path) + } + if retryAfter <= 0 && status == http.StatusTooManyRequests { + retryAfter = retryAfterFromHeaders(resp.Header) + } + } + apiErr.RetryAfter = retryAfter + return apiErr +} + +// resourceFromPath extracts the resource noun and ID from a request path such +// as /api/v2/task/abc123/field/xyz, yielding ("task", "abc123"). +func (c *Client) resourceFromPath(path string) (string, string) { + if c.client != nil && c.client.BaseURL != nil { + path = strings.TrimPrefix(path, c.client.BaseURL.Path) + } + segments := strings.Split(strings.Trim(path, "/"), "/") + name, ok := resourceNames[segments[0]] + if !ok { + return "", "" + } + if len(segments) < 2 { + return name, "" + } + return name, segments[1] +} + +// retryAfterFromHeaders reads the wait time from Retry-After (seconds) or +// ClickUp's X-RateLimit-Reset (unix seconds). +func retryAfterFromHeaders(h http.Header) time.Duration { + if s, err := strconv.Atoi(h.Get("Retry-After")); err == nil && s > 0 { + return time.Duration(s) * time.Second + } + if ts, err := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64); err == nil { + if d := time.Until(time.Unix(ts, 0)); d > 0 { + return d + } + } + return 0 +} diff --git a/internal/api/errors_test.go b/internal/api/errors_test.go new file mode 100644 index 0000000..6cfd2b5 --- /dev/null +++ b/internal/api/errors_test.go @@ -0,0 +1,242 @@ +package api + +import ( + "context" + stderrors "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + "time" + + "github.com/raksul/go-clickup/clickup" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/timimsms/cu/internal/errors" +) + +// errorServer replies to every request with status, the given headers and a +// ClickUp-style error body. +func errorServer(t *testing.T, status int, body string, headers map[string]string) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for k, v := range headers { + w.Header().Set(k, v) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(server.Close) + return server +} + +func TestHandleError_StatusCodes(t *testing.T) { + tests := []struct { + name string + status int + body string + headers map[string]string + kind error + want string + }{ + { + name: "401 token invalid", + status: http.StatusUnauthorized, + body: `{"err":"Token invalid","ECODE":"OAUTH_025"}`, + kind: errors.ErrNotAuthenticated, + want: "not authenticated or token invalid — run `cu auth login` (HTTP 401 OAUTH_025: Token invalid)", + }, + { + name: "401 team not authorized", + status: http.StatusUnauthorized, + body: `{"err":"Team not authorized","ECODE":"OAUTH_027"}`, + kind: errors.ErrNotFound, + want: `task "abc123" not found, or not accessible with the current token (HTTP 401 OAUTH_027: Team not authorized)`, + }, + { + name: "403", + status: http.StatusForbidden, + body: `{"err":"Forbidden","ECODE":"ACCESS_001"}`, + kind: errors.ErrPermissionDenied, + want: `permission denied for task "abc123" — check your ClickUp access to it (HTTP 403 ACCESS_001: Forbidden)`, + }, + { + name: "404", + status: http.StatusNotFound, + body: `{"err":"Task not found","ECODE":"ITEM_013"}`, + kind: errors.ErrNotFound, + want: `task "abc123" not found (HTTP 404 ITEM_013: Task not found)`, + }, + { + name: "429 with Retry-After", + status: http.StatusTooManyRequests, + body: `{"err":"Rate limit reached","ECODE":"APP_002"}`, + headers: map[string]string{"Retry-After": "30"}, + kind: errors.ErrRateLimited, + want: "ClickUp rate limit exceeded — wait 30s and try again (HTTP 429 APP_002: Rate limit reached)", + }, + { + name: "429 without hints", + status: http.StatusTooManyRequests, + body: `{"err":"Rate limit reached","ECODE":"APP_002"}`, + kind: errors.ErrRateLimited, + want: "ClickUp rate limit exceeded — wait a minute and try again (HTTP 429 APP_002: Rate limit reached)", + }, + { + name: "500", + status: http.StatusInternalServerError, + body: `{"err":"Internal Server Error","ECODE":"SHARD_001"}`, + kind: errors.ErrServer, + want: "ClickUp server error — try again shortly (HTTP 500 SHARD_001: Internal Server Error)", + }, + { + name: "503 with non-JSON body", + status: http.StatusServiceUnavailable, + body: `upstream unavailable`, + kind: errors.ErrServer, + want: "ClickUp server error — try again shortly (HTTP 503)", + }, + { + name: "400", + status: http.StatusBadRequest, + body: `{"err":"Status does not exist","ECODE":"ITEM_102"}`, + kind: errors.ErrInvalidInput, + want: "ClickUp rejected the request (HTTP 400 ITEM_102: Status does not exist)", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := errorServer(t, tt.status, tt.body, tt.headers) + + _, err := newTestClient(t, server).GetTask(context.Background(), "abc123") + require.Error(t, err) + + assert.Equal(t, tt.want, err.Error()) + assert.ErrorIs(t, err, tt.kind) + + var apiErr *errors.APIError + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, tt.status, apiErr.StatusCode) + + var sdkErr *clickup.ErrorResponse + assert.ErrorAs(t, err, &sdkErr, "the SDK error must stay reachable") + }) + } +} + +func TestHandleError_RateLimitError(t *testing.T) { + reset := time.Now().Add(45 * time.Second).Unix() + server := errorServer(t, http.StatusTooManyRequests, `{"err":"Rate limit reached","ECODE":"APP_002"}`, map[string]string{ + "X-RateLimit-Limit": "100", + "X-RateLimit-Remaining": "0", + "X-RateLimit-Reset": strconv.FormatInt(reset, 10), + }) + client := newTestClient(t, server) + + _, err := client.GetTask(context.Background(), "abc123") + require.Error(t, err) + + var sdkErr *clickup.RateLimitError + require.ErrorAs(t, err, &sdkErr) + assert.ErrorIs(t, err, errors.ErrRateLimited) + assert.Contains(t, err.Error(), "ClickUp rate limit exceeded — wait 4") + + // The SDK now refuses further requests locally with a synthetic 403; + // that must still read as a rate limit, not a permission problem. + _, err = client.GetTask(context.Background(), "abc123") + require.Error(t, err) + assert.ErrorIs(t, err, errors.ErrRateLimited) + assert.NotErrorIs(t, err, errors.ErrPermissionDenied) +} + +func TestHandleError_ResourceContext(t *testing.T) { + ctx := context.Background() + body := `{"err":"Not found","ECODE":"X_404"}` + + tests := []struct { + name string + call func(*Client) error + want string + }{ + { + name: "list tasks", + call: func(c *Client) error { _, err := c.GetTasks(ctx, "L1", &TaskQueryOptions{}); return err }, + want: `list "L1" not found`, + }, + { + name: "folder lists", + call: func(c *Client) error { _, err := c.GetLists(ctx, "F1"); return err }, + want: `folder "F1" not found`, + }, + { + name: "team tasks", + call: func(c *Client) error { _, err := c.SearchTeamTasks(ctx, "T1", &TeamTaskQuery{}); return err }, + want: `workspace "T1" not found`, + }, + { + name: "custom field on task", + call: func(c *Client) error { return c.RemoveCustomFieldValue(ctx, "abc", "fld") }, + want: `task "abc" not found`, + }, + { + name: "workspaces", + call: func(c *Client) error { _, err := c.GetWorkspaces(ctx); return err }, + want: `workspace not found`, + }, + { + name: "authorized user", + call: func(c *Client) error { _, err := c.GetCurrentUser(ctx); return err }, + want: `resource not found`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := errorServer(t, http.StatusNotFound, body, nil) + + // Mirror production, where the SDK's base URL has an /api/v2/ prefix. + client := newTestClient(t, server) + base, err := url.Parse(server.URL + "/api/v2/") + require.NoError(t, err) + client.client.BaseURL = base + + err = tt.call(client) + require.Error(t, err) + assert.Equal(t, tt.want+" (HTTP 404 X_404: Not found)", err.Error()) + }) + } +} + +func TestHandleError_PassThrough(t *testing.T) { + t.Run("nil", func(t *testing.T) { + assert.NoError(t, (&Client{}).handleError(nil)) + }) + + t.Run("network error", func(t *testing.T) { + server := httptest.NewServer(http.NotFoundHandler()) + client := newTestClient(t, server) + server.Close() + + _, err := client.GetTask(context.Background(), "abc123") + require.Error(t, err) + + var apiErr *errors.APIError + assert.False(t, stderrors.As(err, &apiErr), "transport failures are not API errors") + var urlErr *url.Error + assert.ErrorAs(t, err, &urlErr) + }) + + t.Run("context canceled", func(t *testing.T) { + err := fmt.Errorf("request: %w", context.Canceled) + assert.Same(t, err, (&Client{}).handleError(err)) + }) + + t.Run("already typed", func(t *testing.T) { + typed := errors.NewAPIError(http.StatusNotFound, "", "", nil) + assert.Same(t, typed, (&Client{}).handleError(typed)) + }) +} diff --git a/internal/errors/errors.go b/internal/errors/errors.go index 30f9f60..56663e4 100644 --- a/internal/errors/errors.go +++ b/internal/errors/errors.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "net/http" + "strings" + "time" ) // Error types @@ -26,105 +28,137 @@ var ( // ErrNotFound indicates the requested resource was not found ErrNotFound = errors.New("resource not found") + // ErrPermissionDenied indicates the token may not access the resource + ErrPermissionDenied = errors.New("permission denied") + // ErrInvalidInput indicates invalid user input ErrInvalidInput = errors.New("invalid input") - // ErrConfigNotFound indicates the configuration was not found - ErrConfigNotFound = errors.New("configuration not found") + // ErrServer indicates ClickUp failed to process a valid request (5xx) + ErrServer = errors.New("ClickUp server error") ) -// APIError represents an error from the ClickUp API +// APIError is a ClickUp API failure translated into a user-facing message. +// It wraps both a category sentinel (Kind) and the original SDK error (Err), +// so errors.Is(err, ErrNotFound) and errors.As(err, &*clickup.ErrorResponse) +// both keep working. type APIError struct { StatusCode int `json:"status_code"` - Message string `json:"message"` - Details string `json:"details,omitempty"` + ECode string `json:"ecode,omitempty"` // ClickUp's ECODE, e.g. OAUTH_025 + Message string `json:"message,omitempty"` // ClickUp's "err" text + + // Resource and ResourceID name what the request was about ("task", + // "abc123") when it can be derived from the request path. + Resource string `json:"resource,omitempty"` + ResourceID string `json:"resource_id,omitempty"` + + // RetryAfter is how long until the rate limit resets, when known. + RetryAfter time.Duration `json:"-"` + + Kind error `json:"-"` + Err error `json:"-"` } -func (e *APIError) Error() string { - if e.Details != "" { - return fmt.Sprintf("API error (%d): %s - %s", e.StatusCode, e.Message, e.Details) +// NewAPIError classifies a failed ClickUp response. err is the original +// error and is preserved for unwrapping. +func NewAPIError(statusCode int, ecode, message string, err error) *APIError { + e := &APIError{StatusCode: statusCode, ECode: ecode, Message: message, Err: err} + + switch { + case statusCode == http.StatusUnauthorized && isTeamNotAuthorized(ecode, message): + // ClickUp answers 401 "Team not authorized" when the token is fine but + // the resource belongs to a workspace it can't see, which is also what + // a mistyped ID looks like. Treat it as not found, not as a login issue. + e.Kind = ErrNotFound + case statusCode == http.StatusUnauthorized: + e.Kind = ErrNotAuthenticated + case statusCode == http.StatusForbidden: + e.Kind = ErrPermissionDenied + case statusCode == http.StatusNotFound: + e.Kind = ErrNotFound + case statusCode == http.StatusTooManyRequests: + e.Kind = ErrRateLimited + case statusCode >= 500: + e.Kind = ErrServer + case statusCode == http.StatusBadRequest: + e.Kind = ErrInvalidInput } - return fmt.Sprintf("API error (%d): %s", e.StatusCode, e.Message) + return e } -// NewAPIError creates a new API error -func NewAPIError(statusCode int, message string, details ...string) *APIError { - err := &APIError{ - StatusCode: statusCode, - Message: message, - } - if len(details) > 0 { - err.Details = details[0] - } - return err +func isTeamNotAuthorized(ecode, message string) bool { + return ecode == "OAUTH_027" || strings.Contains(strings.ToLower(message), "team not authorized") } -// UserError represents a user-friendly error message -type UserError struct { - Message string - Suggestion string - Err error +func (e *APIError) Error() string { + return e.summary() + e.detail() } -func (e *UserError) Error() string { - if e.Suggestion != "" { - return fmt.Sprintf("%s\n\nSuggestion: %s", e.Message, e.Suggestion) +// summary is the user-facing explanation of what went wrong. +func (e *APIError) summary() string { + target := e.target() + switch { + case e.Kind == ErrNotFound && e.StatusCode == http.StatusUnauthorized: + if target == "" { + target = "resource" + } + return target + " not found, or not accessible with the current token" + case e.Kind == ErrNotFound: + if target == "" { + return "resource not found" + } + return target + " not found" + case e.Kind == ErrNotAuthenticated: + return "not authenticated or token invalid — run `cu auth login`" + case e.Kind == ErrPermissionDenied: + if target == "" { + return "permission denied — check your ClickUp access to this resource" + } + return "permission denied for " + target + " — check your ClickUp access to it" + case e.Kind == ErrRateLimited: + if e.RetryAfter > 0 { + return fmt.Sprintf("ClickUp rate limit exceeded — wait %s and try again", e.RetryAfter.Round(time.Second)) + } + return "ClickUp rate limit exceeded — wait a minute and try again" + case e.Kind == ErrServer: + return "ClickUp server error — try again shortly" + case e.Kind == ErrInvalidInput: + return "ClickUp rejected the request" + default: + return "ClickUp request failed" } - return e.Message } -func (e *UserError) Unwrap() error { - return e.Err +// detail keeps the raw status, ECODE and ClickUp message visible for +// debugging and bug reports, e.g. " (HTTP 401 OAUTH_025: Token invalid)". +func (e *APIError) detail() string { + d := fmt.Sprintf("HTTP %d", e.StatusCode) + if e.ECode != "" { + d += " " + e.ECode + } + if e.Message != "" { + d += ": " + e.Message + } + return " (" + d + ")" } -// NewUserError creates a new user-friendly error -func NewUserError(message, suggestion string, err error) *UserError { - return &UserError{ - Message: message, - Suggestion: suggestion, - Err: err, +func (e *APIError) target() string { + if e.Resource != "" && e.ResourceID != "" { + return fmt.Sprintf("%s %q", e.Resource, e.ResourceID) } + return e.Resource } -// HandleHTTPError converts HTTP status codes to appropriate errors -func HandleHTTPError(statusCode int, body string) error { - switch statusCode { - case http.StatusUnauthorized: - return NewUserError( - "Authentication failed", - "Run 'cu auth login' to authenticate", - ErrNotAuthenticated, - ) - case http.StatusForbidden: - return NewUserError( - "Access denied", - "Check your permissions for this resource", - NewAPIError(statusCode, "Forbidden", body), - ) - case http.StatusNotFound: - return NewUserError( - "Resource not found", - "Check the ID or name and try again", - ErrNotFound, - ) - case http.StatusTooManyRequests: - return NewUserError( - "Rate limit exceeded", - "Please wait a moment and try again", - ErrRateLimited, - ) - case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable: - return NewUserError( - "ClickUp service error", - "The service is temporarily unavailable. Please try again later", - NewAPIError(statusCode, "Service Error", body), - ) - default: - if statusCode >= 400 { - return NewAPIError(statusCode, "Request failed", body) - } - return nil +// Unwrap exposes both the category sentinel and the original error. +func (e *APIError) Unwrap() []error { + var errs []error + if e.Kind != nil { + errs = append(errs, e.Kind) + } + if e.Err != nil { + errs = append(errs, e.Err) } + return errs } // IsRetryable determines if an error is retryable diff --git a/internal/errors/errors_test.go b/internal/errors/errors_test.go index ddc0665..f32e611 100644 --- a/internal/errors/errors_test.go +++ b/internal/errors/errors_test.go @@ -3,99 +3,99 @@ package errors import ( "errors" "testing" + "time" "github.com/stretchr/testify/assert" ) -func TestAPIError(t *testing.T) { - t.Run("NewAPIError creates error", func(t *testing.T) { - err := NewAPIError(404, "Not Found", "Resource not found") - assert.NotNil(t, err) - assert.Equal(t, 404, err.StatusCode) - assert.Equal(t, "Not Found", err.Message) - assert.Equal(t, "Resource not found", err.Details) - }) - - t.Run("APIError formats message", func(t *testing.T) { - err := NewAPIError(500, "Internal Server Error", "Database connection failed") - assert.Contains(t, err.Error(), "500") - assert.Contains(t, err.Error(), "Internal Server Error") - assert.Contains(t, err.Error(), "Database connection failed") - }) -} - -func TestUserError(t *testing.T) { - t.Run("NewUserError creates error", func(t *testing.T) { - err := NewUserError("Invalid token", "Try logging in again", ErrInvalidToken) - assert.NotNil(t, err) - assert.Equal(t, "Invalid token", err.Message) - assert.Equal(t, "Try logging in again", err.Suggestion) - assert.Equal(t, ErrInvalidToken, err.Err) - }) - - t.Run("UserError formats with suggestion", func(t *testing.T) { - err := NewUserError("Authentication failed", "Run 'cu auth login'", ErrNotAuthenticated) - assert.Contains(t, err.Error(), "Authentication failed") - assert.Contains(t, err.Error(), "Suggestion: Run 'cu auth login'") - }) - - t.Run("UserError without suggestion", func(t *testing.T) { - err := NewUserError("Something went wrong", "", nil) - assert.Equal(t, "Something went wrong", err.Error()) - }) -} +func TestNewAPIError(t *testing.T) { + cause := errors.New("sdk error") -func TestHandleHTTPError(t *testing.T) { tests := []struct { - name string - statusCode int - body string - expectedMsg string + name string + statusCode int + ecode string + message string + resource string + resourceID string + kind error + want string }{ { - name: "401 Unauthorized", - statusCode: 401, - body: "unauthorized", - expectedMsg: "Authentication failed", + name: "401 token invalid", + statusCode: 401, ecode: "OAUTH_025", message: "Token invalid", + kind: ErrNotAuthenticated, + want: "not authenticated or token invalid — run `cu auth login` (HTTP 401 OAUTH_025: Token invalid)", }, { - name: "403 Forbidden", - statusCode: 403, - body: "forbidden", - expectedMsg: "Access denied", + name: "401 team not authorized is not a login problem", + statusCode: 401, ecode: "OAUTH_027", message: "Team not authorized", + resource: "task", resourceID: "bogus", + kind: ErrNotFound, + want: `task "bogus" not found, or not accessible with the current token (HTTP 401 OAUTH_027: Team not authorized)`, }, { - name: "404 Not Found", - statusCode: 404, - body: "not found", - expectedMsg: "Resource not found", + name: "403 with resource", + statusCode: 403, resource: "list", resourceID: "42", + kind: ErrPermissionDenied, + want: `permission denied for list "42" — check your ClickUp access to it (HTTP 403)`, }, { - name: "429 Rate Limited", - statusCode: 429, - body: "rate limited", - expectedMsg: "Rate limit exceeded", + name: "404 with resource", + statusCode: 404, ecode: "ITEM_013", message: "Task not found", + resource: "task", resourceID: "abc", + kind: ErrNotFound, + want: `task "abc" not found (HTTP 404 ITEM_013: Task not found)`, }, { - name: "500 Server Error", - statusCode: 500, - body: "internal error", - expectedMsg: "ClickUp service error", + name: "404 without resource", + statusCode: 404, + kind: ErrNotFound, + want: "resource not found (HTTP 404)", + }, + { + name: "429", + statusCode: 429, + kind: ErrRateLimited, + want: "ClickUp rate limit exceeded — wait a minute and try again (HTTP 429)", + }, + { + name: "500", + statusCode: 500, message: "Internal error", + kind: ErrServer, + want: "ClickUp server error — try again shortly (HTTP 500: Internal error)", + }, + { + name: "400", + statusCode: 400, ecode: "INPUT_005", message: "Status not found", + kind: ErrInvalidInput, + want: "ClickUp rejected the request (HTTP 400 INPUT_005: Status not found)", + }, + { + name: "other 4xx", + statusCode: 409, + want: "ClickUp request failed (HTTP 409)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := HandleHTTPError(tt.statusCode, tt.body) - assert.Error(t, err) - assert.Contains(t, err.Error(), tt.expectedMsg) + err := NewAPIError(tt.statusCode, tt.ecode, tt.message, cause) + err.Resource, err.ResourceID = tt.resource, tt.resourceID + + assert.Equal(t, tt.want, err.Error()) + assert.ErrorIs(t, err, cause, "original error must stay reachable") + if tt.kind != nil { + assert.ErrorIs(t, err, tt.kind) + } }) } +} - t.Run("200 OK returns nil", func(t *testing.T) { - err := HandleHTTPError(200, "success") - assert.NoError(t, err) - }) +func TestAPIErrorRetryAfter(t *testing.T) { + err := NewAPIError(429, "", "", nil) + err.RetryAfter = 42*time.Second + 300*time.Millisecond + assert.Equal(t, "ClickUp rate limit exceeded — wait 42s and try again (HTTP 429)", err.Error()) } func TestIsRetryable(t *testing.T) { @@ -116,22 +116,22 @@ func TestIsRetryable(t *testing.T) { }, { name: "429 API error", - err: NewAPIError(429, "Too Many Requests"), + err: NewAPIError(429, "", "Too Many Requests", nil), expected: true, }, { name: "503 API error", - err: NewAPIError(503, "Service Unavailable"), + err: NewAPIError(503, "", "Service Unavailable", nil), expected: true, }, { name: "502 API error", - err: NewAPIError(502, "Bad Gateway"), + err: NewAPIError(502, "", "Bad Gateway", nil), expected: true, }, { name: "404 API error", - err: NewAPIError(404, "Not Found"), + err: NewAPIError(404, "", "Not Found", nil), expected: false, }, { @@ -162,7 +162,8 @@ func TestPredefinedErrors(t *testing.T) { assert.Error(t, ErrNetworkError) assert.Error(t, ErrRateLimited) assert.Error(t, ErrNotFound) + assert.Error(t, ErrPermissionDenied) assert.Error(t, ErrInvalidInput) - assert.Error(t, ErrConfigNotFound) + assert.Error(t, ErrServer) }) }