npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ipcom/try-state

v0.1.4

Published

Utility function for error handling in TypeScript

Downloads

323

Readme

@ipcom/try-state

npm version

A utility function for handling asynchronous operations with error handling in TypeScript.

Features

  • Wraps asynchronous operations in a consistent try-catch pattern.
  • Captures and returns error details (message, stack, function name, etc.).
  • Provides execution metadata (execution time and timestamp).
  • Designed for TypeScript with full type support.

Why Use @ipcom/try-state?

Traditionally, when handling asynchronous operations, you need to use try-catch blocks repeatedly, which can make the code verbose and harder to read. With @ipcom/try-state, you can simplify error handling and keep your code clean and consistent.

Example: Using Traditional try-catch

const fetchData = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Math.random() > 0.5 ? resolve('Success') : reject(new Error('Random Error'));
    }, 500);
  });
};

(async () => {
  try {
    const result = await fetchData();
    console.log('Success:', result);
  } catch (error) {
    console.error('Error occurred:', error.message);
    console.error('Stack trace:', error.stack);
  }
})();

Example: Using @ipcom/try-state

import tryState from '@ipcom/try-state';

const fetchData = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Math.random() > 0.5 ? resolve('Success') : reject(new Error('Random Error'));
    }, 500);
  });
};

(async () => {
  const [data, error] = await tryState(fetchData, 'Default Value');

  if (error) {
    console.error('Error occurred:', error.message);
    console.error('Error location:', error.location);
  } else {
    console.log('Success:', data);
  }
})();

Key Differences

  1. Readability:
    tryState eliminates repetitive try-catch blocks, making the code cleaner and easier to read.

  2. Error Handling:
    With tryState, error details (like the message and stack trace) are encapsulated in a structured way, reducing the need for manual error parsing.

  3. Metadata:
    Unlike try-catch, tryState provides additional metadata like execution time and timestamp, which are useful for monitoring and debugging.

By replacing verbose try-catch blocks with @ipcom/try-state, you improve code maintainability while maintaining robust error handling.


Installation

Install the package via npm:

npm install @ipcom/try-state

Usage

Here’s an example of how to use tryState in your project:

Example 1: Basic Usage

import tryState from '@ipcom/try-state';

const fetchData = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Math.random() > 0.5 ? resolve('Success') : reject(new Error('Random Error'));
    }, 500);
  });
};

(async () => {
  const [data, error, meta] = await tryState(fetchData, 'Default Value');

  if (error) {
    console.error('Error occurred:', error.message);
    console.error('Error location:', error.location);
    console.error('Execution time:', meta?.executionTimeMs, 'ms');
    console.error('Timestamp:', meta?.timestamp);
  } else {
    console.log('Success:', data);
    console.log('Execution time:', meta?.executionTimeMs, 'ms');
    console.log('Timestamp:', meta?.timestamp);
  }
})();

Example 2: Handling API Calls

import axios from 'axios';
import tryState from '@ipcom/try-state';

const fetchFromAPI = async () => {
  const response = await axios.get('https://api.example.com/data');
  return response.data;
};

(async () => {
  const [data, error] = await tryState(fetchFromAPI, []);

  if (error) {
    console.error('Failed to fetch API data:', error.message);
  } else {
    console.log('API Data:', data);
  }
})();

Example 3: Additional Context in Errors

import tryState from '@ipcom/try-state';

const performTask = async () => {
  throw new Error('Simulated Task Error');
};

(async () => {
  const [data, error] = await tryState(
    performTask,
    'Default Value',
    { taskId: 1234, taskType: 'simulation' }
  );

  if (error) {
    console.error('Task Failed:', error.message);
    console.error('Context:', error.taskId, error.taskType);
  }
})();

API

tryState

A utility function for handling asynchronous operations with error handling.

Parameters

  1. fn (Function):
    A function that returns a Promise<T>. This is the asynchronous operation to be executed.

  2. initialValue (T):
    A fallback value to return in case of an error.

  3. additionalContext (optional):
    A key-value object to include in the error context. It is useful for debugging and tracking additional information.

Returns

A Promise resolving to a tuple:

  1. T (result):
    The result of the operation, or the initialValue if an error occurs.

  2. ErrorProps | null (error):
    An object containing error details, or null on success. The ErrorProps object includes:

  • message: A string describing the error.
  • stack: The error stack trace.
  • function: The function name where the error occurred.
  • location: The relevant stack line for the error.
  1. { executionTimeMs: number; timestamp: string }? (metadata):
    Optional metadata about the operation:
  • executionTimeMs: The time taken to execute the operation (in milliseconds).
  • timestamp: A timestamp indicating when the operation started.

Example Return

Here’s an example of the tuple returned by tryState:

[
  'Success',         // Result of the operation
  null,              // No error
  {                  // Metadata
    executionTimeMs: 502,
    timestamp: '2024-11-23T16:00:00.000Z'
  }
]

Contributing

Contributions are welcome! 🎉
If you have an idea to improve this package, found a bug, or want to add a new feature, feel free to contribute. Here's how you can help:

  1. Report Issues:
    Found a bug or have a feature request? Open an issue on the GitHub Issues page.

  2. Submit Pull Requests:
    If you'd like to contribute code, fork the repository and submit a pull request. Make sure to:

  • Follow the existing code style.
  • Add tests for new features or bug fixes.
  • Update the documentation if necessary.
  1. Improve Documentation:
    Help make this package easier to use by improving the documentation.

  2. Discuss Ideas:
    Have an idea but not sure how to implement it? Start a discussion by creating an issue or reaching out.

How to Contribute

To contribute, follow these steps:

  1. Fork the repository and clone it to your local machine:
git clone https://github.com/<your-username>/try-state.git
cd try-state