TypedError ⌨️💥
A better JavaScript Error for Node.js, Deno and the browser.
Built with ❤️ at Think-it.Abstract
Error handling is a tough subject. And it’s even more difficult when dealing with
large projects.
The JavaScript Error
is a necessary component of the error handling story, but it’s often too limited.
The main difficulty is categorizing errors; when building the main business logic
of any project, it’s common to encounter similar errors (e.g. duplicate entities,
forbidden access, etc.), and relying on
Error.prototype.message
is quite restrictive.
TypedError aims to solve this issue, providing a extra TypedError.prototype.type.
The type field is typed through TypeScript, allowing
a smoother error handling story.
Usage
Node.js
Install via npm or yarn
npm install @think-it-labs/typed-erroryarn add @think-it-labs/typed-errorDeno
Import as ES module
import { TypedError } from "https://deno.land/x/typederror/mod.ts"Then it’s possible to create a custom Error class extending the TypedError
enum MyErrorType {
Unknown,
HTTP,
}
export class MyError extends TypedError<MyErrorType> {}
Now, during error handling code can inspect the type error and define behavior accordingly
import { MyError, MyErrorType } from "./my-error"
export function errorHandling(error: unknown) {
if (error instanceof MyError) {
switch (error.type) {
case MyErrorType.HTTP: {
// handle http errors
}
case MyErrorType.Unknown:
default: {
// red alert: unknown behavior
}
}
}
}
License
TypedError is distributed under the terms of the MIT license.
See LICENSE for details.