Skip to content

Commit

Permalink
Support error instance
Browse files Browse the repository at this point in the history
  • Loading branch information
blond committed Jan 18, 2016
1 parent 166e5f9 commit 9d74f4f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
You can't use `throw` statement in expressions in JavaScript:

```js
arg = arg || throw new Error('arg is required');
arg = arg || throw new Error('arg is required');
// => SyntaxError: Unexpected token throw
```

Expand All @@ -14,13 +14,19 @@ var thr = require('throw');

// ...

arg = arg || thr('arg is required');
arg = arg || thr('arg is required');
```

Messages can contain `printf`-like placeholders:

```js
arg = arg || thr('"%s" is required', argName);
arg = arg || thr('"%s" is required', argName);
```

You can specify instance of `Error` instead of message:

```js
arg = arg || thr(new Error('arg is required'));
```

## Installation
Expand Down
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ var format = require('util').format;
/**
* Function wrapper for throw statement.
* Throw an error with formatted message.
* @param {String} errorMessage
* @param {Error|String} error — instance of error or error message.
* @throws
*/
module.exports = function(errorMessage) {
module.exports = function(error) {
if (error instanceof Error) {
throw error;
}

throw new Error(format.apply(null, arguments));
};

0 comments on commit 9d74f4f

Please sign in to comment.