DEV Community

Cover image for Handling API Errors Safely with a Wrapper Function
Danilo Assis for Woovi

Posted on

Handling API Errors Safely with a Wrapper Function

In the realm of software development, working with APIs is a common and often essential task. However, APIs aren't infallible; they can encounter errors, and handling these errors gracefully is crucial for maintaining a robust application. In this blog post, we'll delve into a piece of TypeScript code designed to handle API errors effectively by wrapping API calls. Let's explore how this wrapper function works and why it's valuable.

The Problem

Imagine you're building an application that interacts with an external API, let's call it the System Foo API. This API requires authentication using an OAuth token, which is stored in a Redis cache. However, there's a catch - if the API call fails due to an invalid OAuth token, you need to clean up the cache to ensure subsequent requests can be made successfully.

The Solution: systemFooApiSafe

To address this problem, a TypeScript function called systemFooApiSafe is crafted. Let's break down this function:

export const systemFooApiSafe = async <Args extends readonly unknown[], T extends DataResponse<unknown>>(
    fn: (...args: Args) => Promise<T>,
    account: IAccount,
) =>
async (...args: Args): Promise<T> => {
    const result = await fn(...args);

    if (!invalidOAuth(result)) {
        return result;
    }

    await clearToken({ account });

    return result;
};
Enter fullscreen mode Exit fullscreen mode

How it Works:

Input Parameters:

fn: This is the original function that makes the API call.
account: Object representing the account associated with the API.

Return Type:

This function returns a new asynchronous function that wraps the original API call.

Function Execution:

The wrapped function is executed with the provided arguments (...args).
The result of the API call is stored in the result.

Error Handling:

If the OAuth token is deemed invalid based on the response, the invalidOAuth function is called.

If the OAuth token is invalid, the cache is cleared using the clearToken function.

The original result is then returned.

Checking OAuth Token Validity

To determine if the OAuth token is invalid, the invalidOAuth function is employed. Let's dissect this function:

export const invalidOAuth = (
    result: DataResponse<{ erro?: string }>,
) => {
    if (result.response.status === 401) {
        return true;
    }

    if (result.response.status === 429) {
        return true;
    }

    return false;
};
Enter fullscreen mode Exit fullscreen mode

This function inspects the response from the API call and checks for specific error statuses that indicate issues with the OAuth token. If the status is 401 (Unauthorized) or if the status is 429 (Too Many Requests), the function returns true, indicating an invalid OAuth token.

Clearing the Token Cache

In case of an invalid OAuth token, the clearToken function is invoked to remove the token from the Redis cache:

export const fiduciaClearToken = async ({
    account,
}: FiduciaClearTokenArgs) => {
    await RedisCache.del(account.id);
};
Enter fullscreen mode Exit fullscreen mode

Requesting a New Token

In scenarios where the API call fails due to an invalid OAuth token, it's essential to provide users with a seamless experience for recovering from this error. After clearing the token cache, users may need to request a new OAuth token to continue their interactions with the API. Incorporating a mechanism within your application to facilitate this process can greatly enhance user satisfaction and streamline the recovery workflow. Whether it's through a user interface prompt or an automated token refresh mechanism, ensuring that users have a straightforward way to request a new token empowers them to swiftly resume their activities without unnecessary friction.

Conclusion

Wrapping API calls with error-handling logic is a prudent approach to ensure the reliability and resilience of your applications. The handleApiSafe function presented here encapsulates this error-handling mechanism, providing a robust solution for dealing with API errors, particularly those related to OAuth token validation. By incorporating such techniques into your codebase, you can enhance the stability and usability of your applications when interacting with external APIs.


If you want to work in a startup in its early stages, This is your chance. Apply today!


Visit us Woovi!


Photo of Pop & Zebra na Unsplash

Top comments (0)