@kraftr/errors
v0.5.0
Published
<div id="top"></div>
Downloads
0
Maintainers
Readme
Very lightweight library with no dependencies to handle errors in a typed way
🚨🚨 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
- 2. 🚀 Install
- 3. 👨💻 Usage
- 4. 💪 Strongly typed
- 5. 🚶♂️ When to use
- 6. Enforce the usage
- 7. 📚 Acknowledgments
- 8. 🔍 Related Projects
- 9. 🤝 License
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
- Checked and Unchecked Exceptions in Java
- Expressive error handling in TypeScript and benefits for domain-driven design
- 200 OK! Error Handling in GraphQL
- STOP throwing Exceptions!
- Flexible Error Handling w/ the Result Class
8. 🔍 Related Projects
9. 🤝 License
Distributed under the MIT License. See LICENSE.txt
for more information.