How to handle ClearRun SDK errors (HostedApiError)
Any non-2xx reply rejects with HostedApiError. Read err.status and err.code to decide what to do. A missing key rejects with MissingApiKeyError instead, on the first score, evaluate or chat call.
Last updated
Applies to version 1.2.0 of @clearrun/sdk and @clearrun/cli.
Steps
Catch and branch
import { HostedApiError, MissingApiKeyError } from '@clearrun/sdk'; try { const { verdict } = await client.score({ responseText }); } catch (err) { if (err instanceof HostedApiError) { if (err.status === 429) { /* wait err.retryAfter seconds, then retry */ } else if (err.status === 402) { /* needs err.creditsNeeded, has err.currentBalance */ } else if (err.status === 401 || err.status === 403) { /* key or plan */ } else { console.error(err.status, err.code, err.message); } } else if (err instanceof MissingApiKeyError) { // no key configured } else { throw err; } }
What is on the error
| Field | Example |
|---|---|
status | 429 |
message | Rate limit exceeded |
code | CONTENT_BLOCKED, CONTENT_TOO_LONG and so on, or undefined when the API sent none. It is an open string, not a fixed list |
details | Extra data, when the API sends a details object |
retryAfter | On a 429: seconds to wait, from the reply body or the Retry-After header |
creditsNeeded, currentBalance | On a 402: what the call needs and what you have, from the reply body |
retryAfter, creditsNeeded and currentBalance are set only when the reply includes them.