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

ts-throws

v2.0.0

Published

A tiny library that allows you to wrap functions with documented error checking. Optionally, you can force consumers of a given function to handle errors.

Downloads

169

Readme

ts-throws

A tiny library that allows you to wrap functions with documented error checking. Optionally, you can force consumers of a given function to handle errors.

Example

yarn add ts-throws

import { throws } from 'ts-throws';

class StringEmptyError {}
class NoAsdfError {}

const getStringLength = throws(
  (str: string) => {
    if (!str.trim()) throw new StringEmptyError();
    if (str === 'asdf') throw new NoAsdfError();
    
    return str.length;
  },
  { StringEmptyError, NoAsdfError }
)

throws adds a try function which will force you to catch the provided errors. It will also allow direct invocations by calling the function normally. This avoids breaking changes, and allows developers to opt-in when desired. It dynamically generates catch* methods based on the object of errors you provide. The error names will be automatically capitalized.

let length = getStringLength.try(' ')
  .catchStringEmptyError(err => console.error('String is empty'))
  .catchNoAsdfError(err => console.error('String cannot be asdf'));

// length is undefined, logged 'String is empty'

length = getStringLength.try('asdf')
  .catchStringEmptyError(err => console.error('String is empty'))
  .catchNoAsdfError(err => console.error('String cannot be asdf'));

// length is undefined, logged 'String cannot be asdf'

length = getStringLength.try(' ')
  .catchStringEmptyError(err => console.error('String is empty'))

// Only one error caught, length is:
// { catchNoAsdfError: (err: NoAsdfError) => void) => number | undefined }
// Function logic not invoked until last error is handled with `.catch`

length = getStringLength.try('hello world')
  .catchStringEmptyError(err => console.error('String is empty'))
  .catchNoAsdfError(err => console.error('String cannot be asdf'));

// length is 11

// Example direct invocation:
length = getStringLength('hello world');
// length is 11

throwsUnsafe

If you don't want to allow direct invocations, you can force consumers to handle errors properly via throwsUnsafe:

import { throwsUnsafe } from 'ts-throws';

class StringEmptyError {}
class NoAsdfError {}

const getStringLength = throwsUnsafe(
  (str: string) => {
    if (!str.trim()) throw new StringEmptyError();
    if (str === 'asdf') throw new NoAsdfError();

    return str.length;
  },
  { StringEmptyError, NoAsdfError }
)

// Cannot directly call getStringLength
getStringLength('bing bong'); // TypeError

// You have to call .try
getStringLength
  .try('bing bong')
  .catchStringEmptyError(() => { /* ... */ })
  .catchNoAsdfError(() => { /* ... */ })

Async functions

It's plug-and-play:

import { throws } from 'ts-throws';

export class BadResponseError {}

const getResponse = throws(
  async () => {
    const response = await fetch('https://some-url.com');
    if (!response.ok) throw new BadResponseError();
    
    return str.length;
  },
  { BadResponseError }
);

const response = await getResponse.try()
  .catchBadResponseError(err => {
    // Received 400+ error
  });

if (!response) return;

console.log(response); // -> Response

Of course, if you don't catch the right errors you're still blocked from using the provided function.

Usage without custom error classes

You can provide regular expressions or strings to match thrown errors.

const getStringLength = throws(
  (str: string) => {
    if (!str.trim()) throw new Error('String is empty');
    if (str === 'asdf') throw 'cannot be asdf';

    return str.length;
  },
  { StringEmptyError: /is empty/, NoAsdfError: 'cannot be asdf' }
);

getStringLength.try(' ')
  .catchStringEmptyError(err => {
    // Note: `err` is going to be `unknown` in both of these cases.
    console.error('String is empty')
  })
  .catchNoAsdfError(err => {
    console.error('No asdf error')
  });

// -> Logs "String is empty"

getStringLength.try('asdf')
  .catchStringEmptyError(err => {
    console.error('String is empty')
  })
  .catchNoAsdfError(err => {
    console.error('No asdf error')
  });

// -> Logs "No asdf error"

When a string or regex is provided as the matcher, ts-throws will check the following:

  • error.name
  • error.message
  • The entire error if it's a string

String matcher checks use .include, they are not converted to a RegExp before testing.

Functions that return errors instead of throwing

ts-throws handles this by trying to match the return value against each provided error. In fact, this method is encouraged over throwing if possible. Handling returned errors is ~2x faster than thrown errors.

const getStringLength = throws(
  (str: string) => {
    if (!str.trim()) return new Error('String is empty');
    if (str === 'asdf') return 'cannot be asdf';

    return str.length;
  },
  { StringEmptyError: /is empty/, NoAsdfError: 'cannot be asdf' }
);

getStringLength.try(' ')
  .catchStringEmptyError(err => {
    // Note: `err` is going to be `unknown` in both of these cases.
    console.error('String is empty')
  })
  .catchNoAsdfError(err => {
    console.error('No asdf error')
  });

// -> Logs "String is empty"

getStringLength.try('asdf')
  .catchStringEmptyError(err => {
    console.error('String is empty')
  })
  .catchNoAsdfError(err => {
    console.error('No asdf error')
  });

// -> Logs "No asdf error"

const length = getStringLength.try('hello')
  .catchStringEmptyError(err => {
    console.error('String is empty')
  })
  .catchNoAsdfError(err => {
    console.error('No asdf error')
  });

// `length` is 5

Of course, this works with custom error classes as well.

Pitfalls

  • class CustomError extends Error {}

    Extending Error causes a significant performance hit (~80%). If you don't need things like Error.stack, you probably don't need to extend it anyway.