Skip to main content
The Paystack SDK uses a unique error handling pattern that combines TypeScript’s type safety with Zod’s runtime validation. Unlike traditional try-catch approaches, methods return a result object that contains either data or an error.

The Result Pattern

All SDK methods return a result object with two properties:
Either data or error will be defined, never both. This pattern eliminates the need for try-catch blocks in most cases.

Basic Error Handling

Here’s how to handle responses from the SDK:

Types of Errors

The SDK handles three main categories of errors:

Validation Errors

Input data fails Zod schema validation before the API request

API Errors

Paystack API returns an error response (4xx, 5xx status codes)

Network Errors

Connection issues, timeouts, or network failures

1. Validation Errors

Zod validates all inputs before making API requests. If validation fails, you’ll receive a detailed error:

Validation Error Structure

Zod errors provide detailed information:

2. API Errors

When Paystack returns an error response, the SDK parses it and returns the error in the result. Here’s the implementation from src/main/transaction.ts:119-124:
src/main/transaction.ts

Common API Errors

The request contains invalid parameters.
Invalid or missing API key.
The requested resource doesn’t exist.
Rate limit exceeded.
Paystack server error (rare).

3. Network Errors

Network errors occur outside the SDK’s control and should be caught with try-catch:

Error Handling Patterns

Pattern 1: Simple Check

For basic operations where you just need to know if it succeeded:

Pattern 2: Detailed Error Handling

When you need granular control:

Pattern 3: Type Guards

Use TypeScript type guards for safer code:

Pattern 4: Centralized Error Handler

Create a reusable error handler:

Framework Integration

Best Practices

Always Check Errors First

Check for result.error before accessing result.data to avoid undefined errors.

Log Errors Completely

Log the full error object for debugging, but show user-friendly messages to users.

Use Try-Catch for Network

Wrap SDK calls in try-catch to handle network errors.

Don't Swallow Errors

Always handle or propagate errors. Never silently ignore them.

Debugging Errors

The SDK logs API error responses to the console automatically. Check src/main/fetcher.ts:65-67:
src/main/fetcher.ts
This helps you debug issues during development.

Enable Detailed Logging

Next Steps

Type Safety

Learn about TypeScript types and runtime validation

Transactions

Explore the Transactions API