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

@sbsto/safe

v0.1.1

Published

A library to help you escape try-catch hell.

Downloads

2

Readme

safe

A library to help save people from try-catch hell.

Example 1: safe

In typescript, it can be difficult to manage handling different types of error. For example, you might want to handle an IncorrectPassword error differently to a UserNotFound error.

import { safe } from "@sbsto/safe";

enum SignInError {
  IncorrectPassword = "IncorrectPassword",
  UserNotFound = "UserNotFound",
}

import { customLogger }  from './logger';

/**
  * Setting `DEBUG=1` in your .env will cause `safe` to log on errors.
  * It defaults to `console` as the logger, but you may pass a custom one if you prefer.
  */
const signInSafe = safe<SignInError>({ logger: customLogger }); 

async function signIn(email: string, password: string) {
  const user = await db.select(user).where({ email: "[email protected]" });
  if (!user) {
    return signInSafe.fail(SignInError.UserNotFound);
  }

  if (user.passwordHash !== hashPassword(password)) {
    return signInSafe.fail(SignInError.IncorrectPassword);
  }

  return signInSafe.ok(input);
}

// Then, we can handle these accordingly & type-safely, e.g. in a route handler
export const handler = (req: Request) => {
  const signInResult = await signIn(req.body.email, req.body.password);

  // First, we check if it's OK
  if (signInResult.ok) {
    return redirect("/dashboard");
  }

  // Then, we know it's one of two errors
  if (signInResult.error === SignInError.UserNotFound) {
    return redirect("signup");
  }

  // Here, we know they entered the wrong password
  return response(403);
};

The above is probably bad security. But you get the idea. This might seem trivial here (it probably wouldn't be so bad to just do with with functions, e.g. trying to find the user, doing something if that fails, then verifying the password, doing something if that fails, otherwise continuing. But I like to encapsulate all of that in the parent function, without giving up a type-safe way to handle each error variant. This also becomes useful when your errors can propagate through many functions (e.g. a parent's safe can account for the error types from multiple children's safes).

Example 2: catcher

Imagine you have a function with a return that depends on two fallible operations.

Here's how you'd use catcher to manage this.

import { catcher } from "@sbsto/safe";

function fallibleOperation() {
  return "hello world";
}

function fallibleAsyncOperation(data: string) {
  return Promise.resolve("hello world");
}

async function getTwoResultsExample() {
  const result1 = catcher(fallibleOperation);
  if (!result1.ok) {
    return result1.error; // handle first error here
  }

  const result2 = await catcher(() => fallibleAsyncOperation(result1.data));
  if (!result2.ok) {
    return result2.error; // handle second error here
  }

  return [result1, result2];
} // inferred return type is Promise<Result<[Result<string, Error>, Result<string, Error>], Error>>

As opposed to this:

async function getTwoResultsWithoutCatcher() {
  try {
    const result1 = fallibleOperation(); // try can fail here
    const result2 = await fallibleAsyncOperation(result1); // or here
    return [result1, result2];
  } catch (e) {
    return e; // so we can't handle the error differently for each operation
  }
} // inferred return type is Promise<unknown>

// or this:

async function getTwoResultsWithoutCatcherTwo() {
  try {
    const result1 = fallibleOperation(); // try can fail here
    try {
      const result2 = await fallibleAsyncOperation(result1); // or here
      return [result1, result2];
    } catch (e) {
      return e; // handle second error here
    }
  } catch (e) {
    return e; // handle first error here
  }
} // inferred return type is Promise<unknown>

The catcher has a couple benefits:

  • It has better type inferrence for the parent function
  • It allows you to specifically handle as many fallible operations as you need without deeply nested try-catch.