Provides a nicer way to handle errors avoiding ugly native try {} catch (e) {}
indentation.
const { tryCatch } = require('co-try-catch');
function *getData() {
const response = yield tryCatch(makeAsyncRequest(options));
if (response.failed()) {
/* handle error */
return /* and stop function execution */;
}
/* continue with the normal function execution */
console.log(response.getResult());
}
...also, if you prefer...
const { err, result } = yield tryCatch(makeAsyncRequest(options));
Returns if function has thrown an error
Returns if function didn't throw an error
alias of isError()
alias of isSuccess()
Returns the thrown object
Returns result of the function execution
if a function call returns an instance of TryCatchResult
it is passed up to the caller
const { tryCatch } = require('co-try-catch');
co(function*() {
const exception = function *() { thrown new Error('test'); }
const fn1 = function *() { return yield tryCatch(exception()); };
const fn2 = function *() { return yield tryCatch(fn1)); };
const result = tryCatch(f2());
result.isError().should.equals(true);
result.getError().message.should.equals('test');
});