【发布时间】:2019-12-14 15:36:53
【问题描述】:
我想编写一个用于包装其他函数的函数,以便捕获所有错误,包括由 Promise 拒绝生成的错误(通常需要 .catch Promise 方法)。
目标是能够包装函数,以便处理所有运行时错误。一个示例用法是我们想要运行的功能,但它是可选的,不是核心业务流程的一部分。如果有错误,我们想报告它并稍后修复它,但我们不希望它停止程序流程。
它应该能够用任意数量的参数包装函数,并返回与原始函数相同的值,包括原始函数是否返回一个承诺。
我是否正在处理以下所有可能的情况?有没有更简单的方法来做到这一点?
const catchAllErrors = (fn) => (...args) => {
try {
const possiblePromise = fn(...args);
// Is it a promise type object? Can't use "instanceof Promise" because just
// for example, Bluebird promise library is not an instance of Promise.
if (typeof possiblePromise.catch === 'function') {
return Promise.resolve(possiblePromise).catch((error) => {
console.log('Caught promise error.', error);
});
}
return possiblePromise;
} catch (error) {
console.log('Caught error.', error);
}
};
// EXAMPLE USAGE
// Applying the wrapper to various types of functions:
const throwsErr = catchAllErrors((x, y) => {
throw `Error 1 with args ${x}, ${y}.`;
});
const promiseErr = catchAllErrors((a, b) => Promise.reject(`Error 2 with args ${a}, ${b}.`));
const noError = catchAllErrors((name) => `Hi there ${name}.`);
const noErrorPromise = catchAllErrors((wish) => Promise.resolve(`I wish for ${wish}.`));
// Running the wrapped functions:
console.log(throwsErr(1, 2));
promiseErr(3, 4).then((result) => console.log(result));
console.log(noError('folks'));
noErrorPromise('sun').then((result) => console.log(result));
【问题讨论】:
标签: javascript ecmascript-6 promise try-catch