为什么jQuery在$ .ajax成功回调中吞下异常? [英] Why does jQuery swallow exceptions in $.ajax success callbacks?

查看:87
本文介绍了为什么jQuery在$ .ajax成功回调中吞下异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来jQuery 1.6.4故意吞下$ .ajax成功回调中的异常.

It looks like jQuery 1.6.4 deliberately swallows exceptions in $.ajax success callbacks.

如果我这样做:

$.get('/', function() {console.log('doodoo');})

我在(Chrome)控制台中看到了这个

I get this in the (Chrome) console:

Object
doodoo

但是,如果我这样做,

$.get('/', function() {throw 'doodoo';})

我在控制台中没有看到错误:

I get no error in the console:

Object

快速浏览jQuery源代码显然表明这是故意的:

A quick look at the jQuery source code shows this is obviously intentional:

try {
    while( callbacks[ 0 ] ) {
        callbacks.shift().apply( context, args );
    }
} catch(e) { }

有人知道为什么jQuery会这样做吗?

Does anyone know why jQuery does this?

推荐答案

我在这里,但是原因可能是因为无论如何您都无法捕获该错误.由于它是一个回调,因此您将无法将其包装在try/catch中.如果jQuery没有捕获到它,您的应用程序将崩溃,这很可能不是您想要的.如果您需要检查错误,则将代码包装在回调内的try/catch中.

I'm guessing here, but the reason is probably because you would not be able to catch the error anyway. Since its a callback you would not be able to wrap it in a try/catch. If jQuery didn't catch it, your application would crash, which is most likely not what you want. If you need to check for errors wrap the code in a try/catch inside the callback.

try {
    $.get('/', function() {throw 'doodoo';})
} catch(e) {
    // this wont do anything, even if jQuery didn't catch the error
}

$.get('/', function() {
    try {
        throw 'doodoo';
    } catch(e) {
        // this is the proper way to do it
    }
})

这篇关于为什么jQuery在$ .ajax成功回调中吞下异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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