Skip to main content

Error Handling

The Respectify API follows standard REST conventions for error handling:

  • HTTP 200: Success. Response body contains the documented schema for that endpoint (e.g., CommentScore, SpamDetectionResult).
  • HTTP 4xx/5xx: Error. Response body contains a standard Error object with error, message, and code fields. Errors that an integration should act on without parsing the message also carry a machine-readable error_code.

All language SDKs provide typed exceptions for different error conditions—the libraries wrap HTTP REST interaction and surface errors as exceptions. Catch these to handle specific failure modes in your application.

The three free-plan errors (402 with error_code, 409 and 429) and their exception classes are new in @respectify/client 0.8.0, respectify/respectify-php 0.8.0 and respectify (Python) 0.9.0. Older library versions raise them as PaymentRequiredError, or the base RespectifyError / RespectifyException, with the server's message.

Exception Reference​

AuthenticationError (401)​

AuthenticationError

Raised when your email or API key is invalid, or the API key has been revoked.

Common causes:

  • Typo in email or API key
  • API key was revoked from the dashboard

BadRequestError (400)​

BadRequestError

Raised when the request parameters are invalid.

Common causes:

  • Empty comment text (e.g., passing an empty string to evaluateComment, checkSpam, checkRelevance, etc.)
  • Invalid article ID (malformed UUID, or an ID that doesn't exist)
  • Missing required parameters
  • Invalid comment health tolerances: permissive, relaxed or off on a floored category (threat, identity_attack, sexual_content, harassment), or an unknown item or level. The client also throws BadRequestError for these before sending.

ArticleContextNotFoundError (400)​

ArticleContextNotFoundError (extends BadRequestError)

Raised when an article context ID is well-formed but the server can't find it. Regenerate it with initTopicFromText or initTopicFromUrl and retry the call. See Megacall → Handling Stale Article Contexts.

Common cause: the stored ID was created under a previous API key. Article context IDs are tied to the key that created them.

PaymentRequiredError (402)​

PaymentRequiredError

Raised when your account balance doesn't cover the cost of the call. The call is not run and nothing is charged. The response body has no error_code.

Common causes:

  • Your balance has run out, or is lower than the cost of this call
  • Auto-topup is turned off, or a top-up is still waiting for payment confirmation

What to do: Add balance on your billing page, or turn on auto-topup. See Billing.

A free-plan account that has used up its 200 free comments gets a different 402, below. Check for that one first.

FreeAllowanceExhaustedError (402)​

FreeAllowanceExhaustedError (from @respectify/client 0.8.0), with an upgradeUrl property.

Raised when a free-plan account has used all 200 of its free comments and has no credit. Moderation has stopped for the account: the call is not run and nothing is charged. The body carries error_code free_allowance_exhausted and upgrade_url, the billing page where credit is added:

{
"error": "Free comment allowance used up",
"message": "This account has used all 200 free comments, so moderation has stopped. Add credit to continue, with the same API key: https://respectify.ai/dashboard/billing",
"code": 402,
"error_code": "free_allowance_exhausted",
"upgrade_url": "https://respectify.ai/dashboard/billing"
}

What to do: Decide what your site does while moderation is stopped, and tell the site owner, with the upgrade_url. The WordPress plugin and the Astro integration let comments through unmoderated and notify the owner; see Billing. Do not retry the call: it fails the same way until credit is added. Once it is, the same API key works again with no change to your configuration.

RevisionLimitReachedError (409)​

RevisionLimitReachedError (from @respectify/client 0.8.0)

Raised on the free plan when a comment has been assessed 5 times (the original and 4 revisions), the most the free plan allows for one comment, and a further revision is sent with the same revision token. The call is not run and no free comment is used. The body carries error_code revision_limit_reached:

{
"error": "Revision limit reached",
"message": "This comment has been assessed 5 times, the most the free plan allows. Hold it for the site owner to review.",
"code": 409,
"error_code": "revision_limit_reached"
}

What to do: Stop sending the comment back to the commenter. Hold it for the site owner to review, and tell the commenter it has been sent to the moderators. Paid accounts never get this error.

RateLimitedError (429)​

RateLimitedError (from @respectify/client 0.8.0)

Raised when the server refuses a request because of a rate limit. Free-plan keys may make 30 requests a minute; a request over that gets error_code free_rate_limited and a Retry-After header with the number of seconds to wait:

{
"error": "Too many requests",
"message": "Free plan keys may make 30 requests a minute. Retry after 17 seconds.",
"code": 429,
"error_code": "free_rate_limited"
}

What to do: Wait for the Retry-After interval and retry. The limit is lifted when the account adds credit. The Perspective-compatible suggestscore endpoint has its own 429, for too many score suggestions, with a Google-style body; see Compatibility Details.

UnsupportedMediaTypeError (415)​

UnsupportedMediaTypeError

Raised when calling initTopicFromUrl and the URL points to a file type that Respectify cannot parse.

Supported formats: HTML pages, Markdown files, PDF documents, plain text files.

Common causes:

  • URL points to an image, video, or binary file
  • URL points to a document type like .docx or .xlsx
  • Server returns an unexpected Content-Type header

What to do: Use initTopicFromText instead, or contact us to request support for the format you need.

ServerError (500)​

ServerError

Raised when something goes wrong on the Respectify server, for any 5xx status.

What to do: Retry after a short delay. If the error persists, contact support with the full error message and request details so we can investigate.

HTTP 503 (temporarily unavailable): the Perspective-compatible analyse endpoint returns 503 when scoring is temporarily unavailable. The client libraries raise this as ServerError (ServerException in PHP). Retry after a few seconds, or after the Retry-After interval if the response gives one.

ResponseParseError (TypeScript only)​

ResponseParseError

Raised when the API returns invalid JSON or an unexpected response structure.

What to do: This usually indicates a transient server issue. Retry after a short delay.

Revision Tokens​

On the free plan, a comment counts once however many times the commenter revises it. The server tells revisions apart from new comments with a token:

  1. A free-plan assessment on commentscore, antispam, commentrelevance, dogwhistle or megacall returns the header X-Respectify-Revision-Token, a 43-character token for that comment.
  2. When the commenter revises the comment, send the token back as a request header of the same name, X-Respectify-Revision-Token, on the revised assessment. The revision is not counted as a new comment, and the response carries the same token again for the next revision.
  3. After 5 attempts in all, a further revision with that token gets HTTP 409.
# First assessment: read the token from the response headers
curl -i -X POST https://app.respectify.ai/v0.2/commentscore \
-H "X-User-Email: your@email.com" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"comment": "...", "article_context_id": "..."}'
# ...
# X-Respectify-Revision-Token: 3kP9...43 characters...Qw

# Revision: send it back
curl -X POST https://app.respectify.ai/v0.2/commentscore \
-H "X-User-Email: your@email.com" \
-H "X-API-Key: your-api-key" \
-H "X-Respectify-Revision-Token: 3kP9...Qw" \
-H "Content-Type: application/json" \
-d '{"comment": "...revised...", "article_context_id": "..."}'

Keep the token with the comment on your server (for example in the session or alongside the draft), not in the page, since whoever holds it can spend that comment's remaining attempts. A token the server does not recognise, or one issued to a different API key, is ignored and the request counts as a new comment. A revision that fails, or does no priced work, gives its attempt back.

Paid accounts never receive the header, and sending one does nothing. The Perspective-compatible endpoints have no revision concept and never use it. The WordPress plugin and the Astro integration send the token for you.

The client libraries keep the existing methods and return types unchanged and add a way to read and send the token:

  • TypeScript (@respectify/client 0.8.0): evaluateCommentWithMeta, checkSpamWithMeta, checkRelevanceWithMeta, checkDogwhistleWithMeta and megacallWithMeta return { result, revisionToken }; pass revisionToken in the method's options object on a revision. REVISION_TOKEN_HEADER names the header.
  • PHP (respectify/respectify-php 0.8.0): the result objects of evaluateComment, checkSpam, checkRelevance, checkDogwhistle and megacall implement RevisionTokenCarrier, so $result->getRevisionToken() reads it; each of those methods takes a trailing ?string $revisionToken to send it. A malformed token is refused with BadRequestException before any request is sent.
  • Python (respectify 0.9.0): evaluate_comment_response, check_spam_response, check_relevance_response, check_dogwhistle_response and megacall_response return a RespectifyResponse with .result and .revision_token; every assessing method, including the plain ones, takes revision_token= to send it.

Error Response Format​

All non-200 HTTP responses return a JSON object with this structure:

FieldTypeDescription
errorstringShort error title (e.g., "Unauthorized", "Missing Parameter")
messagestringDetailed error message explaining what went wrong
codeintegerHTTP status code (same as the response status)
error_codestring, optionalMachine-readable reason, present only on errors an integration should act on: free_allowance_exhausted (402), revision_limit_reached (409), free_rate_limited (429)
upgrade_urlstring, optionalWhere to add credit; present only with free_allowance_exhausted

Branch on error_code when it is present, not on message, which may change.

Examples:

{
"error": "Insufficient balance",
"message": "Your balance is $0.0010. This call costs $0.005. Add funds to continue.",
"code": 402
}
{
"error": "Free comment allowance used up",
"message": "This account has used all 200 free comments, so moderation has stopped. Add credit to continue, with the same API key: https://respectify.ai/dashboard/billing",
"code": 402,
"error_code": "free_allowance_exhausted",
"upgrade_url": "https://respectify.ai/dashboard/billing"
}

Basic Error Handling​

import {
RespectifyClient,
AuthenticationError,
BadRequestError,
FreeAllowanceExhaustedError, // from 0.8.0
PaymentRequiredError,
RevisionLimitReachedError, // from 0.8.0
RateLimitedError, // from 0.8.0
UnsupportedMediaTypeError,
ServerError,
} from "@respectify/client";

const client = new RespectifyClient({ email, apiKey });

try {
const result = await client.checkSpam("test comment", articleId);
} catch (e) {
if (e instanceof AuthenticationError) {
console.error(`Auth failed: ${e.message}`);
// Check your email and API key
} else if (e instanceof BadRequestError) {
console.error(`Bad request: ${e.message}`);
// Check comment text isn't empty, articleId is valid
} else if (e instanceof FreeAllowanceExhaustedError) {
console.error(`Free comments used up: ${e.message}`);
// Moderation has stopped. Let the comment through or hold it,
// and tell the site owner to add credit at e.upgradeUrl
} else if (e instanceof PaymentRequiredError) {
console.error(`Payment needed: ${e.message}`);
// Add balance on your billing page
} else if (e instanceof RevisionLimitReachedError) {
console.error(`No more revisions: ${e.message}`);
// Hold the comment for the site owner to review
} else if (e instanceof RateLimitedError) {
console.error(`Rate limited: ${e.message}`);
// Wait for the Retry-After interval, then retry
} else if (e instanceof UnsupportedMediaTypeError) {
console.error(`Unsupported format: ${e.message}`);
// Only raised by initTopicFromUrl
} else if (e instanceof ServerError) {
console.error(`Server error: ${e.message}`);
// Retry after a delay
}
}

Retry Strategies​

For transient errors (5xx), use exponential backoff. For a 429, wait the number of seconds in the Retry-After header instead of guessing; on the free plan that is at most a minute. Do not retry a 402 or a 409: they fail the same way until the account adds credit, or the comment is held for review.

We recommend using established libraries rather than rolling your own:

Use a simple retry wrapper or a library like p-retry:

import { ServerError } from "@respectify/client";

async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3
): Promise<T> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (e) {
if (e instanceof ServerError && attempt < maxRetries) {
await new Promise((r) => setTimeout(r, 2 ** (attempt - 1) * 1000));
continue;
}
throw e;
}
}
throw new Error("Unreachable");
}

const result = await withRetry(() =>
client.checkSpam(comment, articleId)
);