@kraftr/errors
TypeScript icon, indicating that this package has built-in type declarations

0.5.0 • Public • Published

Logo

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

(back to top)

2. 🚀 Install

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

(back to top)

3. 👨‍💻 Usage

@kraft/errors allow keep 2 types of exceptions `UncheckedExceptions` and `CheckedExceptions`.

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.

(back to top)

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
}

(back to top)

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.

(back to top)

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

(back to top)

8. 🔍 Related Projects

(back to top)

9. 🤝 License

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

(back to top)

Package Sidebar

Install

npm i @kraftr/errors

Weekly Downloads

0

Version

0.5.0

License

none

Unpacked Size

56.9 kB

Total Files

26

Last publish

Collaborators

  • mbetancourt