有没有办法在函数中注入 try catch? [英] Is there a way to inject a try catch inside a function?

查看:36
本文介绍了有没有办法在函数中注入 try catch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许你们中的一些人了解 AOP,在某些语言中使用 AOP 可以使您能够在方法执行之后、之前或期间注入代码等.

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.

我想要的是在 Javascript 中应用相同的内容,我目前正在开发一个包含 300 多个 ajax 调用的大型应用程序,每次我需要对它们的 catch 语句进行一些更改时,我都必须修改一个接一个,很乏味.

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.

我想做的是:

functionName.before("try {")

functionName.after("} catch(ex){
//dostuff
}")

有可能吗?我知道每个函数中都有 .call 或参数对象之类的东西..它们看起来非常元函数 (AOP) 功能.

Is it possible? I know there are things like .call, or the arguments object inside every function..which seem pretty meta-function (AOP) functionalities.

推荐答案

不使用 beforeafter,但是 wrap 会起作用:

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);
        }
    };
};

然后像这样使用

var safeFunction = functionName.wrapTry(doStuff);

这篇关于有没有办法在函数中注入 try catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆