@sanely/errors
v0.1.0
Published
Extensible error handling for TypeScript
Downloads
5,101
Maintainers
Readme
@sanely/errors gives each error in your app a class, a string tag, and typed fields. You group the classes in a registry, and then create, wrap, match, and serialize them by tag.
import * as Fault from "@sanely/errors"
class NotFoundError extends Fault.Tagged("NotFoundError")<{ id: string }>() {}
const fault = new NotFoundError({ id: "123" })
.withMessage("User not found")
.withDescription("DB query returned 0 rows")
fault._tag // "NotFoundError"
fault.fields.id // "123"
fault.message // "User not found", for the user
fault.description // "DB query returned 0 rows", for debuggingFeatures
- Tagged subclasses. Each fault type is a real class with a
_tagdiscriminant, soinstanceofworks. - Typed fields. Each fault type has its own structured fields in
fault.fields, so any field name works. - A message and a description.
messageis for the user.descriptiondescribes the error and what happened, for debugging. - Cause chains. Wrap and throw again, and keep the full chain of causes.
- Registries. Group fault types into a union with
create,wrap, andmatchmethods. - Serialization. Convert a fault to a plain object, send it, and build it again on the other side. A registry types the payload by tag.
- No external dependencies.
Install
npm install @sanely/errorsThe package needs TypeScript 5.4 or later, and Node.js 20 or later.
Get started
Define fault classes, group them in a registry, and match them by tag:
import * as Fault from "@sanely/errors"
class NotFoundError extends Fault.Tagged("NotFoundError")<{ id: string }>() {}
class DatabaseError extends Fault.Tagged("DatabaseError")() {}
const AppFault = Fault.registry({ NotFoundError, DatabaseError })
try {
throw AppFault.create("NotFoundError", { id: "123" }).withMessage("User not found")
} catch (error) {
AppFault.matchTags(error, {
NotFoundError: (fault) => console.log(fault.fields.id), // "123", typed as string
DatabaseError: () => console.log("db failed"),
})
}Documentation
How-to guides:
- How to define fault types and group them in a registry
- How to wrap an error and read its cause chain
- How to handle faults by tag
- How to send faults across a boundary
Reference:
Explanation:
Contributing
Read the contributor guide before changing the package.
Acknowledgments
The package is inspired by the Fault library.
Made with 🥐 pastry.
License
MIT. See LICENSE.
