der*_*783 2 javascript error-handling proxy
是否可以使用代理来包装对具有错误处理的对象上的异步方法的调用?
我尝试了下面的代码,但是当代理方法中发生错误时,catch 不会执行。
const implementation = {
// proxied async methods here
}
const proxy = new Proxy(implementation, {
get: (target, prop, reciever) => {
try {
return Reflect.get(target, prop, reciever)
}
catch (error) {
console.log('Error:')
console.error(error)
}
}
})
Run Code Online (Sandbox Code Playgroud)
我的目标是避免在每个代理方法中实现错误处理。
我尝试了一种受 Axel 博士启发的方法(由 Bergi 在问题评论中建议),并且它按预期工作:
const object = {
async foo() {
return new Promise((resolve, reject) => { reject('Boom!') })
}
}
function interceptMethodCalls(obj) {
const handler = {
get(target, propKey, receiver) {
const origMethod = target[propKey];
return async function (...args) {
try {
return await origMethod.apply(this, args);
}
catch (error) {
console.log('Caught:')
console.error(error)
}
}
}
}
return new Proxy(obj, handler);
}
const proxy = interceptMethodCalls(object);
proxy.foo()
Run Code Online (Sandbox Code Playgroud)
上述脚本的输出:
Caught:
Boom!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1253 次 |
| 最近记录: |