Skip to content

denomod/user_error

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

user_error

tag Build Status license

UserError is a base class that makes JavaScript errors a lot more useful. It gives you:

  • A small Error base class for custom errors
  • Support for checking error types using instanceof
  • A correct subclass name property on error objects
  • Cleaner stack traces
  • Native ErrorOptions, including cause

Usage

import UserError from "https://deno.land/x/user_error/mod.ts";

class MyError extends UserError {
  constructor(message: string) {
    super(message);
  }
}

Rationale

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)

License

user_error is released under the MIT License. See the bundled LICENSE file for details.

Thanks

Heavily inspired by mjackson/usererror.

About

UserError is a base class that makes JavaScript/TypeScript errors a lot more useful.

Topics

Resources

License

Stars

3 stars

Watchers

1 watching

Forks

Packages

 
 
 

Contributors