UserError is a base class that makes JavaScript errors a lot more useful. It gives you:
- A small
Errorbase class for custom errors - Support for checking error types using
instanceof - A correct subclass
nameproperty on error objects - Cleaner stack traces
- Native
ErrorOptions, includingcause
import UserError from "https://deno.land/x/user_error/mod.ts";
class MyError extends UserError {
constructor(message: string) {
super(message);
}
}Modern JavaScript runtimes support subclassing Error, but custom error classes
still need boilerplate to set the visible error name.
class MyError extends Error {
constructor(message: string) {
super(message);
}
}
const boom = (): never => {
throw new MyError("boom!");
};
try {
boom();
} catch (error) {
error instanceof Error; // true
error instanceof MyError; // true
error.name; // Error (wrong, should be MyError)
}You can set this.name = "MyError" in every custom error class, but that is
easy to forget and easy to get out of sync when classes are renamed. If you rely
on the default name, logs and serialized errors lose the custom type:
Error: boom! << should be "MyError: boom!"
at boom (test.js:10:9)
at Object.<anonymous> (test.js:14:3)
UserError centralizes that setup. When we run the example with UserError it looks like this:
import UserError from "https://deno.land/x/user_error/mod.ts";
class MyError extends UserError {
constructor(message: string) {
super(message);
}
}
const boom = (): never => {
throw new MyError("boom!");
};
try {
boom();
} catch (error) {
error instanceof Error; // true
error instanceof MyError; // true
error.name; // MyError
}Since both instanceof and the name property work, you can do either
if (error instanceof MyError)
// ...or
if (error.name === 'MyError')
// ...instead of duck-typing with a custom property. Additionally, the stack trace doesn't contain unnecessary entries:
MyError: boom!
at boom (test.js:10:9)
at Object.<anonymous> (test.js:14:3)
user_error is released under the MIT License. See the bundled LICENSE file for details.
Heavily inspired by mjackson/usererror.