0

I'm using Q.js for promises.

I'd like to know if it's possible to quickly format/change the error-message when a Q-promise fails.

Consider the contrived example:

           return Q.when(//$.ajaxpromise for instance).then(function(result){
                    //handle result
                }).fail(function(err){
                    //somehow change err (returned from $.ajax) to something
                    //sensible (say the statuscode + responseText) and
                    //push it up the callstack
                });

Of course I could do the following but it feels kind of cumbersome:

             var deferred = Q.defer(); 
             Q.when( //$.ajaxpromise for instance).then(function(result){
                    //handle result
                    deferred.resolve();
                }).fail(function(err){
                    deferred.reject(new Error(err.responseText));
                });
             return deferred.promise;

Anyway to do this more elegantly?

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137

1 Answers1

1

The wonderful thing about Q promises (and any Promises/A+ implementation) is that you can just throw:

return Q.when(otherPromise)
    .then(function (result) { /* handle result */ })
    .fail(function (err) { throw new Error('A real error!'); });

You can find this information in the "Propagation" section of the Q readme.

Domenic
  • 110,262
  • 41
  • 219
  • 271
  • true, but when `when` or `then` contain async code, any try/catch up the callstack would not be able to catch the thrown error. But he, that wasn't part of the question and I've already got stuff running stable, so here's your tick :) – Geert-Jan May 24 '13 at 08:32