对Javascript中的每个函数使用通用的try-catch吗?

时间:2018-07-03 16:03:19

标签: javascript function try-catch

这些是我的一些函数,我需要编写一个通用函数以查看函数是否正常运行。我尝试使用try / catch方法。但是我只能在每个函数上单独执行此操作。

div.fight

我在try-catch中编写了每个函数。有没有一种方法可以为所有功能编写通用的try-catch。

function fisrt(){
 console.log("First");
};

function second(){
 console.log("Second");
}

function third(){
 console.log("Third");
}
fisrt();
second();
third();

2 个答案:

答案 0 :(得分:2)

您可以定义一个包装函数,将所需的函数作为参数,然后将其包装在try catch中。

routes.MapRoute(
          name: "ShopByCateShopNow",
          url: "part-lookup/{category}/{make}/{year}/{modelprefix}/{modelsuffix}/{submodel}/{engine}",
          defaults: new { controller = "Home", action = "ShopNowPrefixSuffix" }
        );

然后给出您的原始功能:

models = $"{modelprefix}/{modelsuffix}"

您可以使用包装器功能对每一个进行测试:

function wrapper(fn) {
    try {
        fn();
    } catch(error) {
        console.error(error);
    }
}

无需向每个功能添加try catch。

答案 1 :(得分:0)

关于两年前被接受的答案的介绍句子...

您可以定义一个包装函数,将所需的函数作为参数,然后将其包装在try catch中。

...这部分可能包含一种或多种抽象,其中还可以提供对调用失败( catch and exception 子句)的(不同)处理。

>

例如,如果确实提供了一种功能,该功能以一种方式包装函数/方法,该方式不仅提供了 try catch ,而且还考虑了异常处理 ,就可以轻松完成任务,例如OP要求的任务,这些任务主要是关于 可编程方法,这些方法可以自动创建和处理要处理的功能/方法列表 在抑制意外/意外调用失败的同时被调用。

以下示例确实实现了afterThrowingafterFinally这两个method modifier方法,每个方法都以异常处理程序作为第一个参数来处理原始函数/方法。

利用所提供的抽象,方法本身可以归结为 编写reduce功能,该功能通过调用每个函数来处理一系列函数 它自己的一组参数并收集其调用成功状态...

function first(...args) {
  console.log("first :: does succeed :: argsList :", args);
  return args.join(', ');
}
function second(...args) {
  console.log("second :: going to fail :: argsList :", args);
  throw new Error('2nd invocation failed.');
}
function third(...args) {
  console.log("third :: going to fail :: argsList :", args);
  throw new Error('3rd invocation failed.');
}
function fourth(...args) {
  console.log("fourth :: does succeed :: argsList :", args);
  return args.join(', ');
}
function fifth(...args) {
  console.log("fifth :: does succeed :: argsList :", args);
  return args.join(', ');
}


/**
 *  reduce functionality which processes an array of functions.
 */
function collectResultAfterThrowing(collector, fct, idx) {
  function afterThrowingHandler(error, argsArray) {
    // - can access the try-catch exception and the arguments
    //   that have been passed prior to the invocation failure.
    return {
      success: false,
      failure: {
        message: error.toString(),
        argsList: Array.from(argsArray)
      }
    }
  }
  function unifyResult(value) {
    return ((
         value
      && value.hasOwnProperty('success')
      && (value.success === false)
      && value
    ) || { success: true, value });
  }
  collector.results.push(
    unifyResult(fct                         // - modify original function towards an
      .afterThrowing(afterThrowingHandler)  //   `afterThrowing` handling of its try-catch result(s).
      .apply(null, collector.listOfArguments[idx])
    )
    // - an `afterThrowing` modified function does always return either the result of the
    //   original function's invocation or the return value of its 'afterThrowing' handler.
  );
  return collector;
}


/**
 *  reduce functionality which processes an array of functions.
 */
function collectResultAfterFinally(collector, fct, idx) {
  function isError(type) {
    return (/^\[object\s+Error\]$/).test(Object.prototype.toString.call(type));
  }
  function createResult(value) {
    return (isError(value) && {
      success: false,
      message: value.toString()
    } || {
      success: true,
      value
    });
  }
  collector.results.push(
    createResult(fct            // - modify original function towards an
      .afterFinally(() => null) //   `afterFinally` handling of its try-catch result(s).
      .apply(null, collector.listOfArguments[idx])
    )
    // - an `afterFinally` modified function does always return either the result of the
    //   original function's invocation or the try-catch exception of the invocation attempt.
  );
  return collector;
}


// ... two times, each the actual task, 
// ... once based on "afterThrowing" and
// ... once based on "afterFinally" ...

console.log('"afterThrowing" based try-and-catch results :', [

    first,
    second,
    third,
    fourth,
    fifth

  ].reduce(collectResultAfterThrowing, {

    listOfArguments: [
      ['foo', 'bar'],
      ['baz', 'biz'],
      ['buz', 'foo'],
      ['bar', 'baz'],
      ['biz', 'buz']
    ],
    results: []

  }).results
);
console.log('\n\n\n');

console.log('"afterFinally" based try-and-catch results :', [

    first,
    second,
    third,
    fourth,
    fifth

  ].reduce(collectResultAfterFinally, {

    listOfArguments: [
      ['foo', 'bar'],
      ['baz', 'biz'],
      ['buz', 'foo'],
      ['bar', 'baz'],
      ['biz', 'buz']
    ],
    results: []

  }).results
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
  (function (Function) {

    const fctPrototype = Function.prototype;
    const FUNCTION_TYPE = (typeof Function);

    function isFunction(type) {
      return (
           (typeof type == FUNCTION_TYPE)
        && (typeof type.call == FUNCTION_TYPE)
        && (typeof type.apply == FUNCTION_TYPE)
      );
    }
    function getSanitizedTarget(target) {
      return ((target != null) && target) || null;
    }

    function afterThrowing/*Modifier*/(handler, target) {
      target = getSanitizedTarget(target);

      const proceed = this;
      return (

        isFunction(handler) &&
        isFunction(proceed) &&

        function () {
          const context = target || getSanitizedTarget(this);
          const args = arguments;

          let result;
          try {
            result = proceed.apply(context, args);

          } catch (exception) {

            result = handler.call(context, exception, args);
          }
          return result;
        }

      ) || proceed;
    }
    // afterThrowing.toString = () => 'afterThrowing() { [native code] }';

    function afterFinally/*Modifier*/(handler, target) {
      target = getSanitizedTarget(target);

      const proceed = this;
      return (

        isFunction(handler) &&
        isFunction(proceed) &&

        function () {
          const context = target || getSanitizedTarget(this);
          const args = arguments;

          let result, error;
          try {
            result = proceed.apply(context, args);

          } catch (exception) {

            error = exception;

          } // finally { ... }

          result = (error || result);
          handler.call(context, result, args);

          return result;
        }

      ) || proceed;
    }
    // afterFinally.toString = () => 'afterFinally() { [native code] }';

    Object.defineProperty(fctPrototype, 'afterThrowing', {
      configurable: true,
      writable: true,
      value: afterThrowing/*Modifier*/
    });

    Object.defineProperty(fctPrototype, 'afterFinally', {
      configurable: true,
      writable: true,
      value: afterFinally/*Modifier*/
    });

  }(Function));
</script>