Skip to content

Commit

Permalink
Merge branch 'release/1.0.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
jpbaking committed Jul 7, 2018
2 parents 464f320 + 3e70a40 commit 8f62e90
Show file tree
Hide file tree
Showing 15 changed files with 4,488 additions and 12 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ pids
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# my own test-results folder
test-results

# Coverage directory used by tools like istanbul
coverage

Expand Down
28 changes: 28 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"curly": true,
"eqeqeq": true,
"esversion": 6,
"freeze": true,
"futurehostile": true,
"latedef": true,
"maxcomplexity": 10,
"maxdepth": 3,
"maxparams": 5,
"noarg": true,
"nocomma": true,
"nonew": true,
"notypeof": true,
"strict": true,
"undef": true,
"unused": true,
"varstmt": true,
"node": true,
"globals": {
"describe": true,
"it": true,
"before": true,
"after": true,
"beforeEach": true,
"afterEach": true
}
}
20 changes: 10 additions & 10 deletions LICENSE → LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
MIT License
### MIT License

Copyright (c) 2018 Joseph Baking
#### Copyright (c) 2018 Joseph Baking

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.**
208 changes: 206 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,206 @@
# error-extender
error-extender
# error-extender v1.0.0

Simplifies creation of custom `Error` classes for Node.js.

## Features

### "Extending" Errors

It's quite simple! See below:

```javascript
const extendError = require('error-extender');

const AppError = extendError('ServiceError'); // extends `Error` (default)
```

Or... A bit more complex using the second argument _(options)_:

```javascript
const extendError = require('error-extender');

const AppError = extendError('ServiceError', {
defaultMessage: 'An unhandled error has occurred.',
defaultData: { status: 503, message: 'An unhandled error has occurred.' }
});

const ServiceError = extendError('ServiceError', {
parent: AppError, // extends `AppError`
defaultMessage: 'A service error has occurred.',
defaultData: { status: 500, message: 'A service error has occurred.' }
});

const DatabaseError = extendError('DatabaseError', {
parent: ServiceError, // extends `ServiceError`
defaultMessage: 'A service database error has occurred.',
defaultData: { message: 'A service database error has occurred.' }
});

require('assert').deepStrictEqual(
DatabaseError.defaultData, {
status: 500,
message: 'A service database error has occurred.'
});
// no error
```

Yes, `defaultData` merges!

#### `error-extender` Arguments

`error-extender` accepts a single [object literal](https://www.w3schools.com/js/js_objects.asp) as second argument.

The options (object literal keys) are as follows:

| key | expected type |
| ---------------- | ------------------------------------------ |
| `parent` | `Error.prototype` _or one that extends it_ |
| `defaultMessage` | `string` |
| `defaultData` | `any` |

### "Extended Errors"

1) Creates prototype-based `Error` classes (child/subclass) : _"Extended Errors"_.
1) Those _"Extended Errors"_, accepts `cause` (`Error`); very much like how it is with Java `Exception`.
1) Appends stack of `cause` to the bottom of instantiated _"Extended Errors"_ stack.
1) _"Extended Errors"_ constructor & argument _(w/ optional `new`)_:
1) `new ExtendedError(options)`
1) `ExtendedError(options)`

Yes, much like JavaScript's native `Error`, "Extended Errors" can be written/used "factory-like" (without the `new` keyword).

#### "Extended Errors" Arguments (constructor)

"Extended Errors" accepts a single [object literal](https://www.w3schools.com/js/js_objects.asp) as argument:

```javascript
const extendError = require('error-extender');
const ServiceError = extendError('ServiceError');
try {
// ... something throws something
} catch (error) {
throw new ServiceError({
message: 'An error has occurred',
data: { ref: '7e9f876ca116' },
cause: error
});
}
```

The options (object literal keys) are as follows:

| key | alias | expected type |
| :-------- | :---: | ------------------- |
| `message` | `m` | `string` |
| `data` | `d` | `any` |
| `cause` | `c` | `instancedof Error` |

Given the alias, you may construct extended errors by:

```javascript
const extendError = require('error-extender');
const ServiceError = extendError('ServiceError');
try {
// ... something throws something
} catch (error) {
throw new ServiceError({
m: 'An error has occurred',
d: { ref: '7e9f876ca116' },
c: error
});
}
```

**Note**: Aliases are evaluated first; hence if you have both `m` and `message`, if `m`'s value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), then `m`'s value will be used.

#### Instance Properties

As with `Error`, "Extended Errors" would have the following properties:

* `name`
* `message`
* `stack`

... "Extended Errors" shall have the following additiona properties:

* `data` - _(as set in constructor args)_
* `cause` - _(as set in constructor args)_

#### `data` merging w/ `defaultData`

Yes, you heard right, instance `data` merges with `defaultData`!!!

See example below:

```javascript
const extendError = require('error-extender');

const AppError = extendError('ServiceError', {
defaultData: { status: 503, message: 'An unhandled error has occurred.' }
});

const appError = new AppError({ d: { status: 401 } });

require('assert').deepStrictEqual(
appError.data, {
status: 401,
message: 'An unhandled error has occurred.'
});
// no error
```

## The inspiration (thanks [`bluebird`](https://www.npmjs.com/package/bluebird)!):

```javascript
const Promise = require('bluebird');
// ...
const extendError = require('error-extender');
// ...
const ServiceError = extendError('ServiceError');
const ServiceStateError = extendError(
'ServiceStateError',
{ parent: ServiceError });
// ...
function aServiceFunction() {
return new Promise(
function (resolve, reject) {
// ... multiple things that may throw your
// custom "expected" errors
})
.catch(ServiceStateError, function (error) {
// ... your "common way" of handling
// ServiceStateError
// ... then propagate
})
.catch(ServiceError, function (error) {
// ... your "common generc way" of handling
// ServiceError
// ... then propagate
})
.catch(function (error) {
// ... the "catch all"
// ... then propagate
});
}
```

With JavaScript, I felt quite stifled when I was limited to:

1) Do selective/custom handling based on matching messages from `throw new Error('..')`.
1) Return/propagate [JSend](https://labs.omniti.com/labs/jsend)-like responses to function "callers"/"users".
1) ... or whatever error possible passing/handling could be done, throughout functions and callers/users.

With **`error-extender`** with help from [syntactic-sugar](https://en.wikipedia.org/wiki/Syntactic_sugar) from [`bluebird`](https://www.npmjs.com/package/bluebird), you can improve _(or even standardize)_ your way of propagating/handling errors throughout your application.
callers.

## License

### MIT License

#### Copyright (c) 2018 Joseph Baking

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.**
116 changes: 116 additions & 0 deletions main/ErrorExtender.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
'use strict';

const Assert = require('./helpers/Assert');
const validator = Assert.validator;

const hro = require('./helpers/HiddenReadOnly');
const merge = require('./helpers/Merge');

function configurePrototype(ExtendedErrorType, ParentErrorType) {
hro(ExtendedErrorType, 'prototype', Object.create(ParentErrorType.prototype));
hro(ExtendedErrorType.prototype, 'constructor', ExtendedErrorType);
}

function configureName(ExtendedErrorType, newErrorName) {
hro(ExtendedErrorType.prototype, 'name', newErrorName);
const constructorName = `Created by error-extender: "${newErrorName}"`;
hro(ExtendedErrorType.prototype.constructor, 'name', constructorName);
hro(ExtendedErrorType.prototype.constructor, 'toString', () => `[${constructorName}]`);
}

function configureDefaultMessage(ExtendedErrorType, ParentErrorType, defaultMessage) {
let mergedDefaultMessage;
if (validator.isNotBlank(defaultMessage)) {
mergedDefaultMessage = defaultMessage;
} else {
mergedDefaultMessage = ParentErrorType.defaultMessage;
}
hro(ExtendedErrorType.prototype.constructor, 'defaultMessage', mergedDefaultMessage);
}

function configureDefaultData(ExtendedErrorType, ParentErrorType, defaultData) {
let mergedDefaultData;
if (validator.isObject(defaultData) && validator.isObject(ParentErrorType.defaultData)) {
mergedDefaultData = merge(ParentErrorType.defaultData, defaultData);
} else {
mergedDefaultData = defaultData;
}
hro(ExtendedErrorType.prototype.constructor, 'defaultData', mergedDefaultData);
}

function configureProperties(ExtendedErrorType) {
hro(ExtendedErrorType.prototype, 'message', undefined);
hro(ExtendedErrorType.prototype, 'data', undefined);
hro(ExtendedErrorType.prototype, 'cause', undefined);
}

function capture(target, key, keyAlias) {
return target[key] || target[keyAlias];
}

function captureMessage(target, options) {
const message = options && capture(options, 'm', 'message');
let mergedMessage;
if (validator.isNotBlank(message)) {
mergedMessage = message;
} else {
mergedMessage = target.constructor.defaultMessage;
}
hro(target, 'message', mergedMessage);
}

function captureData(target, options) {
const data = (options && capture(options, 'd', 'data'));
let mergedData;
if (validator.isObject(data) && validator.isObject(target.constructor.defaultData)) {
mergedData = merge(target.constructor.defaultData, data);
} else if (!validator.isUndefined(data)) {
mergedData = data;
} else {
mergedData = target.constructor.defaultData;
}
hro(target, 'data', mergedData);
}

function captureCause(target, options) {
const cause = options && capture(options, 'c', 'cause');
if (cause) {
Assert.isError(cause, '`cause` must be a valid `Error` (instanceof)');
hro(target, 'cause', cause);
hro(target, 'stack', `${target.stack}\nCaused by: ${cause.stack || cause.toString()}`);
}
}

function captureProperties(target, options) {
captureMessage(target, options);
captureData(target, options);
captureCause(target, options);
}

function createExtendedErrorType(newErrorName, ParentErrorType, defaultMessage, defaultData) {
function ExtendedErrorType(options = {}) {
Assert.isObject(options, '`options` must be an object literal (ie: `{}`)');
if (!(this instanceof ExtendedErrorType)) {
return new ExtendedErrorType(options);
}
Error.captureStackTrace(this, this.constructor);
captureProperties(this, options);
}
configurePrototype(ExtendedErrorType, ParentErrorType);
configureName(ExtendedErrorType, newErrorName);
configureDefaultMessage(ExtendedErrorType, ParentErrorType, defaultMessage);
configureDefaultData(ExtendedErrorType, ParentErrorType, defaultData);
configureProperties(ExtendedErrorType);
return ExtendedErrorType;
}

function extend(newErrorName, options = { parent: undefined, defaultMessage: undefined, defaultData: undefined }) {
Assert.isNotBlank(newErrorName, '`newErrorName` cannot be blank');
Assert.isObject(options, '`options` must be an object literal (ie: `{}`)');
let parent = options.parent || Error;
Assert.isError(parent, '`options.parent` is not a valid `Error`');
return createExtendedErrorType(newErrorName, parent,
options.defaultMessage, options.defaultData);
}

module.exports = extend;
Loading

0 comments on commit 8f62e90

Please sign in to comment.