Document Stack
Document Stack
Docs

Error Handling

Understand API error codes, error response format, and best practices for handling failures.

Error Response Format

When an API request fails, the response always includes success: false and an error message:

Error Response
{
  "success": false,
  "error": "Template not found"
}

The HTTP status code indicates the category of error, and the error field provides a human-readable description.

HTTP Status Codes

CodeMeaningCommon Cause
200OKRequest succeeded
201CreatedResource created successfully
400Bad RequestInvalid JSON, missing required fields, validation error
401UnauthorizedMissing or invalid API key
403ForbiddenAPI key lacks permissions for this action
404Not FoundTemplate, project, or resource does not exist
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected server error — contact support

Validation Errors

When the request body fails validation, the API returns a 400 status with details about what went wrong:

Validation Error
{
  "success": false,
  "error": "Validation failed: templateId is required"
}

Handling Errors in Code

Always check the success field or HTTP status code before processing the response:

Error Handling Example
import { DocumentStack } from "@document-stack/sdk-node";

const client = new DocumentStack({ apiKey: process.env.DS_API_KEY! });

try {
    const result = await client.generate({
        templateId: "tmpl_abc123",
        data: { name: "Alice" },
    });
    console.log("PDF URL:", result.url);
} catch (error) {
    if (error.status === 401) {
        console.error("Invalid API key — check your credentials");
    } else if (error.status === 404) {
        console.error("Template not found — verify the template ID");
    } else if (error.status === 429) {
        console.error("Rate limited — wait and retry");
    } else {
        console.error("Unexpected error:", error.message);
    }
}

Retry Strategy

For transient errors (429 and 5xx), implement exponential backoff:

  1. Wait 1 second after the first failure
  2. Wait 2 seconds after the second failure
  3. Wait 4 seconds after the third failure
  4. Stop retrying after 3–5 attempts

Retry-After Header

When rate-limited (429), check the Retry-After header for the exact number of seconds to wait before retrying.

Common Mistakes

IssueErrorFix
Missing Authorization header401 UnauthorizedAdd Bearer YOUR_API_KEY header
Wrong Content-Type400 Bad RequestSet Content-Type: application/json
Template ID from another org404 Not FoundUse a template ID belonging to the API key's org
Malformed JSON body400 Bad RequestValidate JSON before sending

Next Steps