0.5.0 • Published 8 years ago

co-try-catch v0.5.0

Weekly downloads
2
License
ISC
Repository
github
Last release
8 years ago

co-try-catch

Provides a nicer way to handle errors avoiding ugly native try {} catch (e) {} indentation.

Example

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));

Api

*tryCatch(gen: Function|Function*|Promise): TryCatchResult

TryCatchResult

isError(): Boolean

Returns if function has thrown an error

isSuccess(): Boolean

Returns if function didn't throw an error

failed(): Boolean

alias of isError()

succeeded(): Boolean

alias of isSuccess()

getError(): Mixed

Returns the thrown object

getResult(): Mixed

Returns result of the function execution

Supports nested calls

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');
});
0.5.0

8 years ago

0.4.0

8 years ago

0.3.0

8 years ago

0.2.1

8 years ago

0.2.0

8 years ago

0.1.2

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago