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

@kraftr/errors

v0.5.0

Published

<div id="top"></div>

Downloads

0

Readme

Very lightweight library with no dependencies to handle errors in a typed way

Playground Link

🚨🚨 ALERT 🚨🚨 This library is part of the kraftr framework (which is under development), until it reaches a stable version this library will remain as alpha and can receive breaking changes

Table of contents

1. ❗Requirements

  • Typescript target es6+ (to extend properly Error class)
  • strictNullCheck

2. 🚀 Install

pnpm i @kraftr/errors or yarn add @kraftr/errors

3. 👨‍💻 Usage

Sometimes exceptions should be handle and checked, ex:

import { Ok, Err } from '@kraftr/errors'
import db from 'any-db'

class FieldError extends Error {}

function createUser(user: User) {
  const creation = shelter(() => db.user.create(user))
  if(creation.isErr) {
    return Err(FieldError)
  }
  return Ok(user)
}

const user = createUser({ name: 'Fuzzy' })

if(user.isOk) {
  console.log('Fuzzy created')
} else {
  console.log('Fuzzy has errors')
}

But sometimes errors (shouldn't | cannot) be handled

import { Ok, Err } from '@kraftr/errors'
import db from 'any-db'

function connectToDb() {
  db.connect('url') // can throw error
}

connectToDb() // even if you caught the error what can you do? you need the database for the next line
const user = db.user.create({ name: 'Fuzzy' })

there is a method called guard, guard is aware that you have properly handled all the results that you created, it is especially useful if you forget always to handle errors. (you can get help from the eslint-plugin to enforce the usage too)

import { Ok, Err, OkErr, shelter, guard } from '@kraftr/errors'

guard(function main() {
  createUser({ name: 'Fuzzy' }) // result without handle
}) // guard check for Results with errors an rethrow the errors if none of .isErr, .isOk is read etc

If you need caught a exception threw for a third party library for some reason you can do

import { Ok, Err, OkErr, shelter } from '@kraftr/errors'
import db from 'any-db'

const connection = shelter(() => db.connect('url'))
if(connection.isOk) {
  const user = db.user.create({ name: 'Fuzzy' })
} else {
  console.log('sorry check the database')
}

I know, up to here it seems like shelter is just a sugar syntax for try..catch but that's not true let's see the next section.

4. 💪 Strongly typed

import { Ok, Err, OkErr } from '@kraftr/errors'

class CannotBeHome extends Error {}

function isNotHome(x: string): OkErr<string, CannotBeHome> {
  if(x === 'home') {
    return Err(CannotBeHome)
  }
  return Ok(x)
}

bad.value().toUpperCase()
//         ^ typescript say is not valid access to void (can throw exception)

bad.value()!.toUpperCase()
//         ^ here we force to use the value now typescript
//           but at runtime is gonna throw an exception

console.log(good.value()) // Good
console.log(good.value().toUpperCase())
//                      ^ Runtime is good but typescript
//                        say here type error
console.log(good.value()!.toUpperCase()) // Good

if(good.isOk) {
  // Good without type errors
  console.log(good.value().toUpperCase())
}
if(!good.isErr) {
  // Works with "not", here is not type errors
  console.log(good.value().toUpperCase())
}

if(bad.isErr) {
  bad.release() // Release the caught exception (same as throw bad.error)
}

But what if we want just work as normal and get typed errors in some situations?

import { Ok, Err, Return, Throws } from '@kraftr/errors'
import db, { Connection, ConnectionError } from 'any-db'

function connectToDb(): Return<Connection, ConnectionError> {
  return db.connect('url') // can throw error
}

const connection = shelter(connectToDb) //  OkErr<Connection, ConnectionError>
if(connection.isErr) {
  connection.error // properly typed as ConnectionError
}

You can either provide type errors for third party functions or the builtin functions

declare global {
  interface JSON {
    parse(text: object): Record<string, unknown> | Throws<SyntaxError>
  }
}
const parsed = shelter(() => JSON.parse('{;'))
if(parsed.isErr) {
  parsed.error // SyntaxError
}

5. 🚶‍♂️ When to use

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception

For unchecked exceptions use 'Return' as type then people can get type suggestion, for checked exceptions you should use Ok & Err or you can just use 'Return' everywhere and keep using as plain js and when you wanna know a type uses a shelter.

6. Enforce the usage

this library has 2 developed eslint rules to enforce the usages

  • no-unused-result // result objects should be handled
  • return-throw // functions with throw should have it type in the return signature

7. 📚 Acknowledgments

8. 🔍 Related Projects

9. 🤝 License

Distributed under the MIT License. See LICENSE.txt for more information.