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, andcodefields. Errors that an integration should act on without parsing the message also carry a machine-readableerror_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)
- TypeScript
- Python
- PHP
AuthenticationErrorAuthenticationErrorUnauthorizedExceptionRaised 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)
- TypeScript
- Python
- PHP
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,relaxedoroffon a floored category (threat,identity_attack,sexual_content,harassment), or an unknown item or level. The client also throwsBadRequestErrorfor these before sending.
BadRequestError
Raised when the request parameters are invalid.
Common causes:
- Empty comment text (e.g., passing an empty string to
evaluate_comment,check_spam,check_relevance, etc.) - Invalid article ID (malformed UUID, or an ID that doesn't exist)
- Missing required parameters
- Invalid comment health tolerances returned by the server:
permissive,relaxedoroffon a floored category (threat,identity_attack,sexual_content,harassment), or an unknown item or level.ModerationToleranceschecks these when constructed and raises Pydantic'sValidationError, so a request built with it is not sent.
BadRequestException
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,relaxedoroffon a floored category (threat,identity_attack,sexual_content,harassment), or an unknown item or level. TheModerationTolerancesconstructor also throwsBadRequestExceptionfor these, before anything is sent.
ArticleContextNotFoundError (400)
- TypeScript
- Python
- PHP
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.
ArticleContextNotFoundError (extends BadRequestError)
Raised when an article context ID is well-formed but the server can't find it. Regenerate it with init_topic_from_text or init_topic_from_url 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.
ArticleContextNotFoundException (extends BadRequestException)
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)
- TypeScript
- Python
- PHP
PaymentRequiredErrorPaymentRequiredErrorPaymentRequiredExceptionRaised 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)
- TypeScript
- Python
- PHP
FreeAllowanceExhaustedError (from @respectify/client 0.8.0), with an upgradeUrl property.
FreeAllowanceExhaustedError (from respectify 0.9.0; extends PaymentRequiredError), with an upgrade_url attribute. Because it is a subclass, an existing except PaymentRequiredError still catches it; put except FreeAllowanceExhaustedError first to tell them apart.
FreeAllowanceExhaustedException (from respectify/respectify-php 0.8.0), with a getUpgradeUrl() method.
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)
- TypeScript
- Python
- PHP
RevisionLimitReachedError (from @respectify/client 0.8.0)RevisionLimitReachedError (from respectify 0.9.0)RevisionLimitReachedException (from respectify/respectify-php 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)
- TypeScript
- Python
- PHP
RateLimitedError (from @respectify/client 0.8.0)RateLimitedError (from respectify 0.9.0), with a retry_after_seconds attribute taken from the Retry-After headerRateLimitedException (from respectify/respectify-php 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)
- TypeScript
- Python
- PHP
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
.docxor.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.
UnsupportedMediaTypeError
Raised when calling init_topic_from_url 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
.docxor.xlsx - Server returns an unexpected Content-Type header
What to do: Use init_topic_from_text instead, or contact us to request support for the format you need.
UnsupportedMediaTypeException
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
.docxor.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)
- TypeScript
- Python
- PHP
ServerErrorServerErrorServerExceptionRaised 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:
- A free-plan assessment on
commentscore,antispam,commentrelevance,dogwhistleormegacallreturns the headerX-Respectify-Revision-Token, a 43-character token for that comment. - 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. - 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/client0.8.0):evaluateCommentWithMeta,checkSpamWithMeta,checkRelevanceWithMeta,checkDogwhistleWithMetaandmegacallWithMetareturn{ result, revisionToken }; passrevisionTokenin the method's options object on a revision.REVISION_TOKEN_HEADERnames the header. - PHP (
respectify/respectify-php0.8.0): the result objects ofevaluateComment,checkSpam,checkRelevance,checkDogwhistleandmegacallimplementRevisionTokenCarrier, so$result->getRevisionToken()reads it; each of those methods takes a trailing?string $revisionTokento send it. A malformed token is refused withBadRequestExceptionbefore any request is sent. - Python (
respectify0.9.0):evaluate_comment_response,check_spam_response,check_relevance_response,check_dogwhistle_responseandmegacall_responsereturn aRespectifyResponsewith.resultand.revision_token; every assessing method, including the plain ones, takesrevision_token=to send it.
Error Response Format
All non-200 HTTP responses return a JSON object with this structure:
| Field | Type | Description |
|---|---|---|
error | string | Short error title (e.g., "Unauthorized", "Missing Parameter") |
message | string | Detailed error message explaining what went wrong |
code | integer | HTTP status code (same as the response status) |
error_code | string, optional | Machine-readable reason, present only on errors an integration should act on: free_allowance_exhausted (402), revision_limit_reached (409), free_rate_limited (429) |
upgrade_url | string, optional | Where 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
- TypeScript
- Python
- PHP
- REST API
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
}
}
from respectify import (
RespectifyClient,
AuthenticationError,
BadRequestError,
FreeAllowanceExhaustedError, # from 0.9.0
PaymentRequiredError,
RevisionLimitReachedError, # from 0.9.0
RateLimitedError, # from 0.9.0
UnsupportedMediaTypeError,
ServerError
)
client = RespectifyClient(email, api_key)
try:
result = client.check_spam("test comment", article_id)
except AuthenticationError as e:
print(f"Auth failed: {e}")
# Check your email and API key
except BadRequestError as e:
print(f"Bad request: {e}")
# Check comment text isn't empty, article_id is valid
except FreeAllowanceExhaustedError as e:
# Must come before PaymentRequiredError, which it extends
print(f"Free comments used up: {e}")
# Moderation has stopped. Let the comment through or hold it,
# and tell the site owner to add credit at e.upgrade_url
except PaymentRequiredError as e:
print(f"Payment needed: {e}")
# Add balance on your billing page
except RevisionLimitReachedError as e:
print(f"No more revisions: {e}")
# Hold the comment for the site owner to review
except RateLimitedError as e:
print(f"Rate limited, retry in {e.retry_after_seconds}s: {e}")
# Wait, then retry
except UnsupportedMediaTypeError as e:
print(f"Unsupported format: {e}")
# Only raised by init_topic_from_url
except ServerError as e:
print(f"Server error: {e}")
# Retry after a delay
use Respectify\RespectifyClientAsync;
use Respectify\Exceptions\UnauthorizedException;
use Respectify\Exceptions\BadRequestException;
use Respectify\Exceptions\FreeAllowanceExhaustedException; // from 0.8.0
use Respectify\Exceptions\PaymentRequiredException;
use Respectify\Exceptions\RevisionLimitReachedException; // from 0.8.0
use Respectify\Exceptions\RateLimitedException; // from 0.8.0
use Respectify\Exceptions\UnsupportedMediaTypeException;
use Respectify\Exceptions\ServerException;
use Respectify\Exceptions\RespectifyException;
$client->checkSpam("test comment", $articleId)
->then(function ($result) {
echo "Success: " . ($result->isSpam ? 'spam' : 'not spam');
})
->otherwise(function ($e) {
if ($e instanceof UnauthorizedException) {
echo "Auth failed: " . $e->getMessage();
} elseif ($e instanceof BadRequestException) {
echo "Bad request: " . $e->getMessage();
} elseif ($e instanceof FreeAllowanceExhaustedException) {
// Moderation has stopped. Let the comment through or hold it,
// and tell the site owner to add credit at $e->getUpgradeUrl()
echo "Free comments used up: " . $e->getMessage();
} elseif ($e instanceof PaymentRequiredException) {
echo "Payment needed: " . $e->getMessage();
} elseif ($e instanceof RevisionLimitReachedException) {
// Hold the comment for the site owner to review
echo "No more revisions: " . $e->getMessage();
} elseif ($e instanceof RateLimitedException) {
// Wait for the Retry-After interval, then retry
echo "Rate limited: " . $e->getMessage();
} elseif ($e instanceof UnsupportedMediaTypeException) {
echo "Unsupported format: " . $e->getMessage();
} elseif ($e instanceof ServerException) {
echo "Server error: " . $e->getMessage();
} elseif ($e instanceof RespectifyException) {
echo "API error: " . $e->getMessage();
} else {
throw $e;
}
});
$client->run();
Check the HTTP status code. Non-200 responses return the Error format:
// 401 Unauthorized
{"error": "Unauthorized", "message": "Invalid credentials", "code": 401}
// 400 Bad Request
{"error": "Bad Request", "message": "Comment cannot be empty", "code": 400}
// 402 Payment Required (balance)
{"error": "Insufficient balance", "message": "Your balance is $0.0010. This call costs $0.005. Add funds to continue.", "code": 402}
// 402 Payment Required (free plan used up)
{"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"}
// 409 Conflict (free plan: 5 attempts used on this comment)
{"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"}
// 429 Too Many Requests (free plan: over 30 requests a minute; also sends Retry-After)
{"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"}
// 415 Unsupported Media Type
{"error": "Unsupported Media Type", "message": "Content type unsupported: image/png", "code": 415}
// 500 Internal Server Error
{"error": "Internal Server Error", "message": "An unexpected error occurred", "code": 500}
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:
- TypeScript
- Python
- PHP
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)
);
Use a retry library such as tenacity:
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
from respectify import ServerError
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=1, max=10),
retry=retry_if_exception_type(ServerError)
)
def check_spam_with_retry(client, comment, article_id):
return client.check_spam(comment, article_id)
Use a promise-based retry approach with ReactPHP:
use Respectify\Exceptions\ServerException;
function withRetry($promise, $maxRetries = 3, $attempt = 1) {
return $promise->otherwise(function ($e) use ($maxRetries, $attempt) {
if ($e instanceof ServerException && $attempt < $maxRetries) {
return React\Promise\Timer\sleep(pow(2, $attempt - 1))
->then(fn() => withRetry($promise, $maxRetries, $attempt + 1));
}
throw $e;
});
}