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

inline-try

v1.0.1

Published

A javascript library for an inline try

Downloads

5

Readme

inline-try

Build Status codecov

What is inline-try?

inline-try is a javascript library for an inline try.

inline-try With Sync Code

Wrap a function with itry and provide error types you want to catch, and you'll receive an array you can unpack to those values, with the appropriate one defined.

If error types are provided, and the function throws with one not specified, it will be thrown.

Error types can be the built-ins, or your own custom error types.

As a special case, if no error types are provided, all will be caught.

const { itry } = require('inline-try');

const [data, fooError] = itry(someFn, FooError);
// If someFn returns successfully, data will be defined.
// If someFn throws a FooError, fooError will be defined.
// If someFn throws any other error, the itry will throw.

// Another example showing any number of errors can be caught
const [data, typeError, fooError] = await itry(someFn, TypeError, FooError);
// If someFn returns successfully, data will be defined.
// If someFn throws a TypeError, typeError will be defined.
// If someFn throws a FooError, fooError will be defined.
// If someFn throws any other error, the itry will throw.

// Example showing special case of catching all errors
const [data, error] = itry(someFn);
// If someFn returns successfully, data will be defined.
// If someFn throws, error will be defined.
// The itry will never throw an error.

Note that you do not call the function - it will be (and needs to be) invoked by inline-try. If your function takes parameters, you can wrap the function in an anonymous arrow function. For example:

const [data, fooError] = itry(() => someFn(1, 2, 3), FooError);

You can wrap any sync logic or code in a function like this.

inline-try With Async Code

Wrap a promise with itry and provide error types you want to catch, and you'll receive an array you can unpack to those values, with the appropriate one defined.

If error types are provided, and the promise rejects with one not specified, it will be thrown.

Error types can be the built-ins, or your own custom error types.

If no error types are provided, all will be caught.

const { itry } = require('inline-try');

const [data, fooError] = await itry(promise, FooError);
// If the promise resolves, data will be defined.
// If the promise rejects with a FooError, fooError will be defined.
// If the promise rejects with any other error, the await will throw.

const [data, typeError, myError] = await itry(promise, TypeError, MyError);
// If the promise resolves, data will be defined.
// If the promise rejects with a TypeError, typeError will be defined.
// If the promise rejects with a FooError, fooError will be defined.
// If the promise rejects with any other error, the await will throw.

const [data, error] = await itry(promise);
// If the promise resolves, data will be defined.
// If the promise rejects, error will be defined.
// The await will never throw an error.

Note that with async functions you await the itry and do call the function in the itry parameter list (since async functions enclose success and failure data in the promise).

Why use inline-try?

  1. Code using this pattern is more readable.
  2. Being forced to specify which types of errors you catch ensures safer code.

Read about it: Making Await More Functional in JavaScript

TLDR contrived example:

const getArticleEndpoint = async (req, res) => {
  // This code is short and readable, and is specific with errors it's catching
  const [article, queryResultError] = await itry(getArticle(slug), QueryResultError);
  if (queryResultsError) {
    return res.sendStatus(404);
  }
  await article.incrementReadCount();
  const json = article.serializeForAPI();
  res.status(200).json(json);
};

Without inline-try there may be a temptation to write this:

const getArticleEndpoint = async (req, res) => {
  // This code looks short and readable, but is not equivalent.
  try {
    const article = await getArticle(slug);
    await article.incrementReadCount();
    const json = article.serializeForAPI();
    res.status(200).json(json);
  } catch (error) {
    // This is catching too much code. If the increment or serialize methods
    // fail, a 404 is confusingly sent and developer time wasted going down
    // the wrong path of looking into the article and slug and get method,
    // when really it could be the other methods.
    res.sendStatus(404);
  }
};

which is catching too much code. And if realized, may then become:

const getArticleEndpoint = (req, res) => {
  // This code feels like it is working against the language -
  // declaring a variable ahead of time to escape a scoping issue
  // of having to attempt our function in a try block - but is correct.
  let article;
  try {
    article = await getArticle(slug);
  } catch (error) {
    // This is still too broad, and could errantly send a 404 for other
    // types of errors (for example a simple typo in the getArticle,
    // which if it were sync would blow up right away, but since it
    // is async now bubbles up here) again potentially wasting developer
    // time going down the wrong path of looking into the article and slug.
    return res.sendStatus(404);
  }
  article.incrementReadCount();
  res.send(article.serializeForAPI());
}

which is better, but still catching too broadly - and especially in the case of async code (where simple programing typos/mistakes/errors do not blow up the program, but get passed along with the rejection path and so neccesitates really strict analysis of these errors).

And so we'd finally get to the equivalent code:

const getArticleEndpoint = (req, res) => {
  // This code feels like it is working against the language -
  // declaring a variable ahead of time to escape a scoping issue
  // of having to attempt our function in a try block - but is correct.
  let article;
  try {
    article = await getArticle(slug);
  } catch (error) {
    // We remember to check the error
    if (error instanceof QueryResultError) {
      // and to early return
      return res.sendStatus(404);
    }
    // and to re-throw the error if not our type
    throw error;
  }
  article.incrementReadCount();
  res.send(article.serializeForAPI());
};

Alternate API

Error types can also be passed to the itry function as an array, rather than as separate parameters. This can make the code look nicer when formatted.

const [data, typeError, myError] = await itry(
  someAsyncFunctionThatIsKindaLong(oh, and, has, some, params),
  [TypeError, MyError]
);

Addtional Utility Methods in inline-try

In addtion to the itry function described above, inline-try includes two other utility helpers for working with async code.

swallow

Swallow returns the value the function / resolution of promise, or else a default value you provide. It will never throw an error. It may also take a function that is called with the error.

const { swallow } = require('inline-try');
const { logError } = require('./logging');

// With Async Functions
const greeting = await swallow(getGreeting(), 'Hey There!', logError);
// If the promise resolves, greeting will be the value.
// If the promise rejects, greeting will be "Hey There!" and logError will be called with the error.
// The await will never throw an error.

// With Sync Functions
const greeting = swallow(getGreeting, 'Hey There!', logError);
// If the function returns successfully, greeting will be the value.
// If the function throws, greeting will be "Hey There!" and logError will be called with the error.
// The swallow will never throw an error.

tapError

tapError is a function that is called with the error only if the function throws / promise rejects. It does not handle the error - the original error is received, but allows some side effect on that error. This is useful when an error traverses through many "layers" in the program (EG, db -> dao -> service -> controller), and each layer may easily perform side-effects regarding what the error means for it without needing to account for its journey.

const { tapError } = require('inline-try');

// With Async Functions
const getOne = data => tapError(db.one(data), logError);
// If the promise resolves, the value will be returned.
// If the promise rejects, the rejected promise will be returned but with the error already logged.

// With Sync Functions
const getOne = data => tapError(() => sync.one(data), logError);
// If the function returns successfully, the value will be returned.
// If the function throws an error, the error will be returned but with the error already logged.

Installation

npm i inline-try

Alternatives / Prior Art

  • fAwait which this was based on, but only focused on async code for promises/await (and did not also support sync functions).