Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する
Core Concepts

Error Handling


When you interact with the PaymentKit API using the Node.js SDK, network issues or invalid parameters can cause operations to fail. The SDK handles these situations by throwing exceptions. Proper error handling is essential for building a reliable application.

This guide explains how to catch and handle errors effectively using standard JavaScript try...catch blocks.

Catching Errors#

All asynchronous methods in the SDK return Promises, allowing you to use async/await syntax and wrap API calls in a try...catch statement to manage potential failures gracefully.

When an API call fails, the SDK throws an error object containing information about the issue. The message property of this error object provides a clear, human-readable description of what went wrong.

Example: Handling a failed request

import payment from '@blocklet/payment-js';

async function safeRetrieveSubscription(subscriptionId) {
try {
// Attempt to retrieve a subscription
const subscription = await payment.subscriptions.retrieve(subscriptionId);
console.log('Subscription retrieved:', subscription);
return subscription;
} catch (error) {
// If the request fails, the error is caught here
console.error(`Failed to retrieve subscription ${subscriptionId}:`, error.message);
// You can add logic here to handle the failure, e.g., show a message to the user
return null;
}
}

// Example usage with a non-existent ID to trigger an error
safeRetrieveSubscription('sub_invalid_id');

In this example, if payment.subscriptions.retrieve fails (e.g., because the ID is incorrect or there's a network problem), the code execution jumps to the catch block, preventing the application from crashing and allowing you to log the error and respond appropriately.

Error Handling Flow#

The following diagram illustrates the typical control flow for an SDK method call:

Success

Failure

Start: Call an SDK method

Attempt API Request

Method returns response data

SDK throws an Error

'catch' block is executed

Access error details (e.g., error.message)


TypeScript Support#

If you are using TypeScript, the SDK provides full type definitions, including for error objects. This allows you to catch specific types of errors for more precise error handling logic, enhancing the robustness of your application.


With a solid understanding of error handling, you are better equipped to build resilient payment integrations. You can now proceed to explore practical implementations in our Usage Guides.