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

  1. 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

What is on the error
FieldExample
status429
messageRate limit exceeded
codeCONTENT_BLOCKED, CONTENT_TOO_LONG and so on, or undefined when the API sent none. It is an open string, not a fixed list
detailsExtra data, when the API sends a details object
retryAfterOn a 429: seconds to wait, from the reply body or the Retry-After header
creditsNeeded, currentBalanceOn 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.

Which to retry

See Which ClearRun errors are safe to retry?