项目作者: jeandesravines

项目描述 :
:rage1: Functional errors interceptions
高级语言: JavaScript
项目地址: git://github.com/jeandesravines/catcher.git
创建时间: 2016-08-16T13:20:42Z
项目社区:https://github.com/jeandesravines/catcher

开源协议:MIT License

下载


Catcher

Build Status
codecov

Functional errors interceptions

Table of contents

Setup

This module can then be installed with yarn:

  1. yarn add @jdes/catcher

Usage

Import module:

  1. /**
  2. * @type {function}
  3. */
  4. const Catcher = require('@jdes/catcher');

API

Methods

resolve(fn: function: [, defaults: = undefined]): *

  • fn: The function to execute and which can throws an Error.
  • direction: The defaults value to return if fn fails

Execute the function fn surrounding with try/catch block.
If all is ok, catcher returns the value returned by fn.

reject(error: Error = new Error())

  • error: The error to throw

Throws the error give in arguments.

Examples

Resolves with “fs” package

  1. const fs = require('fs');
  2. const util = require('util');
  3. const Catcher = require('@jdes/catcher');
  4. // Call fs.accessSync which throws an error with unknown path
  5. const filename = './unknown';
  6. const exists = Catcher.resolve(() => fs.accessSync(filename)) ? true : false;
  7. const promisify = util.promisify;
  8. if (exists) {
  9. promisify(fs.readFile)(filename)
  10. .then((data) => console.log(data))
  11. .catch((error) => console.error(error));
  12. }

Resolve with default value

  1. const Catcher = require('@jdes/catcher');
  2. // Check if the argument is equal to "jimmy" (after transform it to lower case).
  3. // If it is not, it throws an Error.
  4. // The Error is catched by the catcher and returns the default value : false
  5. const isJimmy = (name) => {
  6. if (name.toLowerCase() !== 'jimmmy') {
  7. throw new Error();
  8. }
  9. return true;
  10. };
  11. if (Catcher.resolve(() => isJimmy('Toto'), false)) {
  12. console.log('Hello Jimmy');
  13. } else {
  14. console.error('Who are you?');
  15. }

Reject functionally

  1. const Catcher = require('@jdes/catcher');
  2. // Returns true if name equals "jimmy" or throws an Error
  3. const isJimmy = (name) => {
  4. return name.toLowerCase() === 'jimmy' || Catcher.reject(new Error());
  5. };
  6. try {
  7. if (isJimmy('Toto')) {
  8. console.log('Hello Jimmy');
  9. }
  10. } catch (error) {
  11. console.error('Who are you?');
  12. }