Skip to content

Instantly share code, notes, and snippets.

@yeyuguo
Last active June 1, 2021 02:56
Show Gist options
  • Save yeyuguo/5bdc3518d4d7214a3ed080440840d350 to your computer and use it in GitHub Desktop.
Save yeyuguo/5bdc3518d4d7214a3ed080440840d350 to your computer and use it in GitHub Desktop.
代理对象, 对函数执行进行 try catch 处理
// 简单工厂模式 - 创建对象
function createFactoryProxy(source, handler) {
// todo 扩展成为单例
const resultTmp = {}
var proxyInst = new Proxy(source, {
set(target, property, value, receiver) {
if (Reflect.has(resultTmp, property)) {
throw new Error('已经设置代理属性, 不能再次设置')
} else {
Reflect.defineProperty(resultTmp, property, {
get() {
if (typeof value === 'function') {
return new Proxy(value, {
// 函数执行时, 做 try catch 处理
apply(funTarget, context, arguemntsList) {
try {
Reflect.apply(value, context, arguemntsList)
} catch (error) {
console.log('全局处理报错, 后续函数继续执行 error: ', error);
}
}
})
} else {
return value
}
}
})
}
},
get(target, property, receiver) {
console.log('property: ', property);
try {
const result = Reflect.get(resultTmp, property)
if (!result) {
throw new Error(`属性 ${property} 不存在`)
}
return result
} catch (error) {
console.log('error: ', error);
return function(){}
}
},
...handler
})
return proxyInst
}
// 代理对象
function ProxyObject(source, handler) {
const proxyObj = createFactoryProxy({}, handler)
for(const [key, value] of Object.entries(source)) {
proxyObj[key] = source[key]
}
return proxyObj
}
// 测试开始
function A(){console.log('A')}
function B(){
throw new Error('err B')
console.log('B')
}
function C(){
throw new Error('err C')
console.log('C')
}
var interface = {
a: A,
b: B,
c: C,
e: null
}
// var newObject = new ProxyObject(interface)
// console.log('newObject.a: ', newObject.a);
// newObject.b()
// newObject.c()
var interface = new ProxyObject(interface)
console.log('interface.a: ', interface.a);
interface.b()
interface.e()
interface.d()
interface.c()
interface.a()
// 测试结束
// export {
// ProxyObject
// }
@yeyuguo
Copy link
Author

yeyuguo commented May 31, 2021

todo:

  1. 属性不存在, 加入 try catch 处理;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment