我研究了在打字稿中使用装饰器的错误处理,发现了一个我没想到的行为
function handleError(): any {
return function (_target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
if (typeof original !== 'function') return;
try {
const result = original.apply(this, arguments);
return result;
} catch (e) {
console.error(`An error occurred!\nFunction: ${propertyKey}\nError: ${e}`);
}
};
}
class test {
@handleError()
mightThrow() {
throw 'Oh no, an error occurred!';
}
}
new test().mightThrow();
运行此代码时,我得到以下控制台输出:
An error occurred!
Function: mightThrow
Error: Oh no, an error occurred!
/home/venny/Projects/lol/index.js:28
throw 'Oh no, an error occurred!';
^
Oh no, an error occurred!
(Use `node --trace-uncaught ...` to show where the exception was thrown)
即使我在装饰器函数中发现了错误,为什么我仍然在这里得到标准的 nodejs 未捕获异常控制台输出?