在正确的上下文中捕获异步异常

Catch async exception in correct context

在异步调用中抛出错误时,错误是在 tryAjax() 上下文消失后抛出的,因此永远不会到达我的 catch 子句。

有没有办法正确捕获非同步异常?

function tryAjax(){
     try{
      didItWork(); 
     }
     catch(e){
       // Do something else
     }
    }

function didItWork(){
        $.ajax({
            url: url,
            success: function (res, status, xhr)
            { 
               // Do something
            },
            error: function (e)
            {
                throw new Error('Canvas video not loaded');                
            }
        });
    };
}

您可以在 AJAX

等异步调用中出现任何错误时调用方法
 function didItWork(){
    $.ajax({
        url: url,
        success: function (res, status, xhr)
        { 
           // Do something
        },
        error: function (e)
        {
            logError(e);               
        }
    });
    };
 }

 function logError(e)
 {
     //Perform activity related to error handling
 }

Is there a way to correctly catch a non synchronous exception?

到异常发生时,控制权已经转移,不再在您的 try/catch 范围内。此外,正如您所发现的,jQuery 从 error 回调中捕获并抑制异常。

在这种特定情况下,通常的做法是让 didItWork 接受一个回调或 return 一个承诺,然后调用该回调或 resolve/reject 承诺的值想要(成功)或指示失败的标志值。

这是一个承诺示例:

function tryAjax(){
    didItWork()
        .done(function(data) {
            // All good, use `data`
        })
        .fail(function(err) {
            // Failed, details in `err`
        });
}

function didItWork(){
    var d = new $.Deferred();
    $.ajax({
        url: url,
        success: function (res, status, xhr)
        { 
           d.resolveWith(res);
        },
        error: function (e)
        {
            d.rejectWith(new Error('Canvas video not loaded'));
        }
    });
    return d.promise();
}

我会这样做:(使用延迟对象)

function tryAjax(){

  didItWork().fail(function (e){  // Do something specific})
             .done(function(a,b,c){//all ok}); 
}

function didItWork(){
     return   $.ajax({
            url: url,
            success: function (res, status, xhr)
            { 

            },
            error: function (e)
            {
               //something general           
            }
        });
    };
}