Tiny library that simplifies subclassing and inheriting from Error while keeping the correct name and stack. Also supports constructing from an object of properties. Saves you from boilerplate.
Error for custom error classes with the correct
stack property. Saves you from writing a few lines of boilerplate.
Errorbehavior in tact.
Object.createbreaks the stack trace.
StandardErrorinstance is also an instance of
Errorobject serializes to an empty object (
npm install standard-error
Just require StandardError.js and either use it directly or inherit from it for your custom error class.
StandardError takes a message argument, but in addition to that,
you may give it an object with other properties to be set:
var StandardError = require"standard-error"throw "Not Found" code: 404
The thrown instance of
StandardError will then have both the
message and the
It'll also also have a
name property set to
You can skip the explicit
message argument and give everything as an
object of properties:
message: "Not Found" code: 404
Note: All properties besides
stack will be enumerable for easier
JSON.stringify. That includes the
name property which
will be set from the constructor's name (defaults to
The real benefit of StandardError.js comes from subclassing it to create new error classes and adding custom behavior to them.
Let's create an
HttpError that we can instantiate with the HTTP status code
new HttpError(404)) and have it set the message automatically based on that:
var Http = require"http"var StandardError = require"standard-error"StandardErrorcallthis msg || HttpSTATUS_CODEScode code: codeObjectcreateStandardErrorprototypeconstructor: value: HttpError configurable: true writable: true
Note that you must set the
constructor property like in the above
StandardError.js depends on that to know which functions to skip in the stack
StandardError.js finds out the name (
err.name) of your subclassed error from
its constructor function. However, if you minify your code, you can also set or
change it explicitly:
Now that you've inherited, you can, for example, customize stringifying by
toString on your subclass. To get
new HttpError(404) to print
404 Not Found:
return thiscode + " " + thismessage
StandardError.js is released under a Lesser GNU Affero General Public License, which in summary means:
For more convoluted language, see the