Skarlinski
Skarlinski

Reputation: 2479

Catch async exception in correct context

When throwing an an error in an async call, the error is thrown after the tryAjax() context is gone, therefore never reaching my catch clause.

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

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

Upvotes: 2

Views: 239

Answers (3)

Royi Namir
Royi Namir

Reputation: 148524

I would do this : ( using deferred objects)

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

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074268

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

By the time the exception has occurred, control has already moved on and is no longer within your try/catch. Also, as you've discovered, jQuery catches and suppresses exceptions from within the error callback.

In this specific situation, the usual thing is to have didItWork accept a callback or return a promise, and call that callback or resolve/reject that promise with either the value you want (success) or a flag value indicating failure.

Here's a promise example:

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

Upvotes: 2

Hemant
Hemant

Reputation: 2059

You can invoke a method upon any error in asynchronous calls like 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
 }

Upvotes: 0

Related Questions