js注册处理错误函数

63 阅读1分钟

背景:函数执行过程中发生异常需要手动try...catch,可以注册一个通用的处理错误函数快速调试和捕获错误信息

摘自vuejs设计与实践

//utils.js
let handkeError = null;
export default {
  execFn(fn) {
    callWithErrorHanding(fn, Array.prototype.slice.call(arguments,1));
  },
  //调用该函数注册统一的错误处理函数
  registerErrorHandler(fn) {
    handkeError = fn;
  },
};

function callWithErrorHanding(fn, args) {
  try {
    fn && fn(...args);
  } catch (e) {
    //将捕获到的错误传递给用户的错误处理程序
    handkeError && handkeError(e);
  }
}

使用

//test.js
import utils from './utils.js';

utils.registerErrorHandler((e) => {
  console.log(e);
});

function test(arg1, arg2) {
  console.log({ arg1, arg2 });
  throw new Error('errorInfo');
}

utils.execFn(test, 1, 2);