admin管理员组文章数量:1279145
Is there any way to handle exceptions thrown from AJAX callbacks in jQuery, other than adding a try..catch block to each callback? The error function is not called in this situation.
$.ajax(
{
url: 'myurl.rails',
success: function( data )
{
throw 'Oh no!';
},
error: function ( xhr, textStatus, errorThrown )
{
console.log( 'AJAX call failed', xhr, textStatus, errorThrown );
}
} );
Is there any way to handle exceptions thrown from AJAX callbacks in jQuery, other than adding a try..catch block to each callback? The error function is not called in this situation.
$.ajax(
{
url: 'myurl.rails',
success: function( data )
{
throw 'Oh no!';
},
error: function ( xhr, textStatus, errorThrown )
{
console.log( 'AJAX call failed', xhr, textStatus, errorThrown );
}
} );
Share
Improve this question
asked Apr 27, 2010 at 14:22
MikeWyattMikeWyatt
7,87111 gold badges53 silver badges71 bronze badges
3 Answers
Reset to default 8If you take a look at the non-minified version of jQuery 1.4.2, the relevant lines are 5264 through 5274:
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [xhr, s] );
}
}
jQuery just calls the success
function applied to settings object (if it exists) without any care of what the function returns or throws.
What you can do instead is use jQuery.ajaxSetup()
like so:
jQuery.ajaxSetup({
success: function() {
try {
if ( this.mysuccess ) {
this.mysuccess.apply( this, arguments );
}
}
catch(err) {
// whatever
}
}
});
And use mysuccess
(or whatever you would prefer to call it) instead of success
at the individual jQuery.ajax
calls.
The error
callback is designed to be used when there is a problem with the request itself. According to the docs:
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
So, if instead there is a problem with the data you get back, then you should deal with it within the success
callback - perhaps by logging it to console, or notifying the user.
Have you looked into any of the global AJAX features of jQuery such as ajaxSetup and ajaxError?
本文标签: javascriptExceptions thrown in jQuery AJAX callbacks swallowedStack Overflow
版权声明:本文标题:javascript - Exceptions thrown in jQuery AJAX callbacks swallowed? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741297132a2370882.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论