Error Handling
The DID Spaces SDK provides a set of utility functions to help you standardize error message and status code retrieval from various types of errors that may occur during network requests or other operations. These utilities simplify error handling, allowing you to present consistent feedback to your users.
For more details on how network requests are managed, refer to the HTTP Clients section.
getErrorMessage#
This function extracts a user-friendly error message from different error types, prioritizing specific response bodies before falling back to the generic error message.
Parameters
Name | Type | Description |
---|---|---|
|
| The error object from which to extract the message. It can be an |
Returns
Name | Type | Description |
---|---|---|
|
| The extracted error message, suitable for display. |
Example
import { SpaceClient } from '@arcblock/did-spaces-client';
import { getErrorMessage } from '@arcblock/did-spaces-client/libs/error';
async function handleError(client) {
try {
// Simulate an operation that might throw an error
await client.object.get({ objectId: 'non-existent-object' });
} catch (error) {
const errorMessage = getErrorMessage(error);
console.error('Operation failed:', errorMessage);
}
}
// Assuming 'client' is an initialized SpaceClient instance
// handleError(client);
This example demonstrates how to use getErrorMessage
to obtain a clean error message from a caught exception, which can then be displayed or logged.
getErrorStatusCode#
This function retrieves the HTTP status code from network-related error objects, such as AxiosError
or HTTPError
.
Parameters
Name | Type | Description |
---|---|---|
|
| The error object from which to extract the status code. It can be an |
Returns
Name | Type | Description |
---|---|---|
|
| The HTTP status code associated with the error. |
Example
import { SpaceClient } from '@arcblock/did-spaces-client';
import { getErrorStatusCode } from '@arcblock/did-spaces-client/libs/error';
async function handleStatusCode(client) {
try {
// Simulate an operation that might throw an error with a status code
await client.object.delete({ objectId: 'invalid-id' });
} catch (error) {
const statusCode = getErrorStatusCode(error);
if (statusCode === 404) {
console.warn('Resource not found.');
} else if (statusCode === 401) {
console.error('Authentication required.');
} else {
console.error('An unexpected error occurred with status code:', statusCode);
}
}
}
// Assuming 'client' is an initialized SpaceClient instance
// handleStatusCode(client);
This example illustrates how to use getErrorStatusCode
to retrieve the HTTP status code from an error, enabling specific handling based on the response status.
These error handling utilities provide a robust way to manage and interpret errors returned by the DID Spaces SDK, contributing to more stable and user-friendly applications. Next, explore the File System utilities for common file operations.