@maxtruxa/user-error v2.0.4
@maxtruxa/user-error
npm package that simplifies inheriting from Error.
const UserError = require('@maxtruxa/user-error');
throw new UserError('Hello, World!', {additional: 'information'});Installation
npm install @maxtruxa/user-errorFeatures
- Subclasses
Errorwithout breaking standard behavior. - Like
Error,UserErrortakes a message as first argument. - Add properties by simply passing in an object as second or first argument
- Properties are enumerable.
That means serialization using
JSON.stringifyworks as expected.
Usage
Just require the package to get UserError and either build your own error class on top of it or use it directly.
Direct Usage
const UserError = require('@maxtruxa/user-error');
throw new UserError('oops', {additional: 'information'});Inheriting
const UserError = require('@maxtruxa/user-error');
// Custom error class that takes an additional "error id" as first argument.
function MyError(id, message, properties) {
UserError.call(this, message, properties);
this.id = id;
}
MyError.prototype = Object.create(UserError.prototype, {
constructor: {value: MyError, configurable: true, writable: true}
});
throw new MyError('foo_error', 'oops');When nesting exceptions, the inner exception should be called inner by convention:
try {
throw new UserError('oops');
} catch (err) {
// "MyError" from the inheritance example above.
throw new MyError('internal_error', 'something failed', {inner: err});
}API
new UserError(message, properties)
Create a new error with the specified message and properties.
The resulting object has the following properties:
namemessagestack- additional properties (copied from the
propertiesargument)
name is taken from (in that order):
properties.name(useful for overriding the name without inheriting)this.constructor.prototype.name(useful for minified code)this.constructor.name
message is taken from (in that order):
properties.messagemessage
stack is taken from (in that order):
properties.stack- generated using
Error.captureStackTrace(if available)
message
anything (default = '')
The message property of the error. The value is always converted to a string.
new UserError(); // default
new UserError('test');properties
object (default = {})
Additional properties to be assigned to the error.
new UserError(); // default
new UserError({foo: 'bar'}); // without message
new UserError('test', {baz: 'qux'}); // with messageTests
To run the test suite, install dependencies, then run npm test:
npm install
npm testCoverage reports are generated by running npm run coverage.
Linting is done with npm run lint.