Error Handling
Error Handling
The SDK throws a single error class, RankHikerError, for non-2xx responses and wrapped network failures.
import { RankHikerError } from '@rankhiker/sdk';
RankHikerError fields
RankHikerError extends Error, so it has the usual message, plus:
| Field | Type | Notes |
|---|---|---|
name | string | Always 'RankHikerError'. |
message | string | Human-readable message (uses the API's error field when present). |
status | number (optional) | HTTP status code, when the failure was an HTTP response. |
body | unknown (optional) | Parsed response body, if any. |
endpoint | string (optional) | The path that failed. |
cause | unknown (optional) | Underlying error, set for wrapped network errors. |
err instanceof RankHikerError or err.name === 'RankHikerError'.
getArticleBySlug maps 404 to null
getArticleBySlug is the one method that does not throw on a missing article: a 404 returns null. Any other non-2xx (401, 500, and so on) still throws. So a typical detail page checks for null first, then wraps the call in try/catch for the real failures:
import { createClient, RankHikerError } from '@rankhiker/sdk';
const rh = createClient({ apiKey: process.env.RANKHIKER_API_KEY! });
try {
const post = await rh.getArticleBySlug(slug);
if (!post) {
// 404: render not-found
return renderNotFound();
}
return renderPost(post);
} catch (err) {
if (err instanceof RankHikerError) {
console.error(err.status, err.endpoint, err.message);
}
throw err;
}
Handling auth, server, and network errors
listArticles and the other methods throw on any non-2xx. Inspect err.status to decide what to do:
try {
const posts = await rh.listArticles();
} catch (err) {
if (err instanceof RankHikerError) {
if (err.status === 401) {
// Bad or revoked key, or the X-API-Key header was dropped across a redirect.
// Check the key, and make sure baseUrl is the apex https://rankhiker.com (not www).
} else if (err.status && err.status >= 500) {
// Server error: retry with backoff, or fall back to cached content
} else if (err.status === undefined) {
// Network error (DNS, offline, CORS). err.cause holds the original error.
}
}
}
A 401 in a browser app is most often a www redirect dropping the API key header. Use the default apex baseUrl (https://rankhiker.com, not www) and confirm the key is correct.
Was this article helpful?