Try Function
Wraps a function in a try/catch block.
Installation
$ npm install utils-try-function
Usage
var wrap = ;
wrap( fcn )
Wraps a function
in a try/catch
block.
{throw 'beep boop' ;}var f = ;var out = ;if out instanceof Errorconsole;// returns 'beep boop'
The returned function
has the same signature as the wrapped function
.
{var sum = a + b + c + d;if sum < 10throw 'invalid input arguments. Arguments must sum to a number greater than or equal to 10.' ;return sum;}var f = ;var out = ;// returns 26out = ;// returns <Error>
If provided an asynchronous function
, the returned function
only traps errors
which occur during the current event loop tick.
{if !athrow 'invalid input argument.' ;process;{if !bthrow 'invalid input argument.' ;;}}{console;}var f = ;var out = ;// returns <Error>out = ;// returns undefined
Notes
- Isolating
try/catch
blocks as separate wrappedfunctions
prevents a parent scope from permanently entering optimization hell.
Examples
var isString =wrap = ;{if !throw 'invalid input argument. Must provide a string primitive. Value: `' + str + '`.' ;return 'beep' + str;}{if !throw 'invalid input argument. Must provide a string primitive. Value: `' + str + '`.' ;;{if str !== 'beep'throw 'invalid input argument. String must equal `beep`. Value: `' + str + '`.' ;;}}{if str !== 'beep boop'throw 'huh?' ;}var out f;// Synchronous...f = ;out = ;// returns 'beep boop'out = ;// returns <Error>// Asynchronous...f = ;out = ;// returns undefinedout = ;// returns undefined and then throws
To run the example code from the top-level application directory,
$ node ./examples/index.js
Tests
Unit
Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:
$ make test
All new feature development should have corresponding unit tests to validate correct functionality.
Test Coverage
This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:
$ make test-cov
Istanbul creates a ./reports/coverage
directory. To access an HTML version of the report,
$ make view-cov
License
Copyright
Copyright © 2015. Athan Reines.