有没有办法在函数内部注入try catch? [英] Is there a way to inject a try catch inside a function?
问题描述
也许有些人对AOP有所了解,在某些使用AOP的语言中,可以使您能够在方法执行之后,执行之前或执行过程中注入代码.
我想要在Javascript中应用相同的代码,我目前正在开发一个具有300多个ajax调用的大型应用程序,每次我需要对它们的catch语句进行一些更改时,都必须进行修改他们一个接一个地乏味.
我想做的是这样的:
functionName.before("try {")
functionName.after("} catch(ex){
//dostuff
}")
有可能吗?我知道在每个函数中都存在诸如.call或arguments对象之类的东西.看起来像是元功能(AOP)功能.
不适用于before
和after
,但是wrap
可以使用:
Function.prototype.wrapTry = function(handle) {
var fn = this;
return function() {
try {
return fn.apply(this, arguments);
} catch(e) {
return handle(e);
}
};
};
然后像使用它
var safeFunction = functionName.wrapTry(doStuff);
Maybe some of you know about AOP, in some languages using AOP can lead you to be able to inject code after, before, or while a method is executing,etc.
What I want is to apply the same in Javascript, I am currently working on a massive app which has more than 300 ajax calls, and every time I need to do some change on the catch statement on them, I have to modify them one by one which is very tedious.
What I want to do is something like :
functionName.before("try {")
functionName.after("} catch(ex){
//dostuff
}")
Is it possible? I know there are things like .call, or the arguments object inside every function..which seem pretty meta-function (AOP) functionalities.
Not with before
and after
, but a wrap
will work:
Function.prototype.wrapTry = function(handle) {
var fn = this;
return function() {
try {
return fn.apply(this, arguments);
} catch(e) {
return handle(e);
}
};
};
Then use it like
var safeFunction = functionName.wrapTry(doStuff);
这篇关于有没有办法在函数内部注入try catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!