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

luoluo-rust-error

v0.0.7

Published

[deprecated] Rust-like error handling in TypeScript

Downloads

3

Readme

luoluo-rust-error

See https://github.com/yyhhenry/jsr-rust-result.

Rust-like error handling in TypeScript.

Provides Result<T, E> and Ok<T> and Err<E> types.

Use Ok() and Err() to create Result<T, E> values.

Works well with TypeScript's type narrowing.

Use rustError() and rustErrorAsync() to wrap your functions that may throw errors.

Feel free to add filters to these two.

Best Practice

import { Ok, Err, Result, rustError } from 'luoluo-rust-error';

function getStatusBase(): string {
  const condition = Math.floor(Math.random() * 3);
  // Some progress that may fail or give out some unexpected result,
  // .e.g. network request
  if (condition === 0) {
    throw new Error('error');
  } else if (condition === 1) {
    return '+';
  }
  return '200';
}

// Before
export function getStatus1(): { status: number } | { error: string } {
  let result: string | undefined = undefined;
  // Variables are nullable
  // In this case, non-nullable type can be inferred, but it is not always possible, especially when there are some lambda functions
  try {
    result = getStatusBase();
  } catch (error) {
    return { error: 'Cannot get status' };
  }
  let status: number | undefined = undefined;
  // So many try-catch blocks
  try {
    status = parseInt(result);
  } catch (error) {
    return { error: 'malformed status' };
  }
  return { status };
}
export function getStatus2(): { status: number } | { error: string } {
  // One giant try-catch block
  // Uneasy to judge the error type
  // May catch some unexpected errors
  try {
    const result = getStatusBase();
    const status = parseInt(result);
    return { status };
  } catch (error) {
    return { error: 'Unknown error' };
  }
}

// After
export function getStatus(): Result<number, string> {
  const result = rustError(getStatusBase)();
  // Variables are non-nullable and errors are solved at once, with type inference
  // The caught error is the expected error
  if (!result.ok) {
    return Err('Cannot get status');
  }
  const status = rustError(parseInt)(result.v);
  if (!status.ok) {
    return Err('malformed status');
  }
  return Ok(status.v);
}

Basic Usage

import { Ok, Err, Result, rustError } from 'luoluo-rust-error';

// Never-throwing function usage
function neverThrowFunc(err: boolean): Result<string, Error> {
  if (err) {
    return Err(new Error('error'));
  }
  return Ok('ok');
}
function neverThrowTest(err: boolean) {
  const result = neverThrowFunc(err);
  if (result.ok) {
    console.log(`Ok(${result.v})`);
  } else {
    console.log(`Err(${result.e.message})`);
  }
}
neverThrowTest(true); // Err(error)
neverThrowTest(false); // Ok(ok)

// Wrapped function usage
type ErrorEnum = 'TypeError' | 'SyntaxError';
function normalFunc(err?: ErrorEnum): string {
  if (err === 'TypeError') {
    throw new TypeError('type error');
  } else if (err === 'SyntaxError') {
    throw new SyntaxError('syntax error');
  }
  return 'ok';
}
const isTypeError = (e: unknown): e is TypeError => e instanceof TypeError;
function wrapTest(err?: ErrorEnum) {
  try {
    // The filter can be omitted, but the type of result will be `Result<string, unknown>`
    const result = rustError(normalFunc, isTypeError)(err);
    if (result.ok) {
      console.log(`Ok(${result.v})`);
    } else {
      console.log(`Err(TypeError(${result.e.message}))`);
    }
  } catch (error) {
    console.log(`UnwrapErr(${error})`);
  }
}

wrapTest('TypeError'); // Err(TypeError(type error))
wrapTest('SyntaxError'); // UnwrapErr(SyntaxError: syntax error)
wrapTest(); // Ok(ok)

// Wrapped built-in function usage
const isSyntaxError = (e: unknown): e is SyntaxError =>
  e instanceof SyntaxError;
const safeParseJSON = rustError(
  (text: string) => JSON.parse(text) as unknown,
  isSyntaxError,
);
function testSafeParseJSON(text: string) {
  const result = safeParseJSON(text);
  if (result.ok) {
    console.log(`Ok(${JSON.stringify(result.v)})`);
  } else {
    console.log(`Err(SyntaxError(${result.e.message}))`);
  }
}
testSafeParseJSON('{"a":1}'); // Ok({"a":1})
testSafeParseJSON('{a:1}'); // Err(SyntaxError(Unexpected token a in JSON at position 1))
testSafeParseJSON(''); // Err(SyntaxError(Unexpected end of JSON input))
testSafeParseJSON('1'); // Ok(1)
testSafeParseJSON('{"a":'); // Err(SyntaxError(Unexpected end of JSON input))