解决错误不工作

Resolve error not working

我正在使用 ui.router 和 Restangular。 在 $stateProvider 我有状态

resolve: {
    dane: function (daneTematy) {
        var promise = daneTematy.getItem(-1);
        return promise;
    }
}

对于测试,它总是产生错误并执行 $stateChangeError

这是服务的功能:

function getItem(id, params) {
    return Restangular.one(zrodlo, id).get()
        .then(getItemSuccess)
        .catch(restangularError);

    function getItemSuccess(response) {
        $log.info('Mam dane elementu - Źródło: ' + zrodlo);
        response.doHistorii();
        return response;
    }
}

function restangularError(response) {
    $log.error("Error with status code", response.status);
    return response;
}

它不起作用 - 它到达 restangularError 但没有到达 $stateChangeError。当我删除 catch 时效果很好:

function getItem(id, params) {
    return Restangular.one(zrodlo, id).get()
        .then(getItemSuccess);

    function getItemSuccess(response) {
        $log.info('Mam dane elementu - Źródło: ' + zrodlo);
        response.doHistorii();
        return response;
    }
}

restangularError 有什么问题?如何解决?

在您的错误处理程序中,您将错误标记为已解决。所以 ui-router 得到了一个已解决的承诺,因此不会导致 $stateChangeError。 要解决此问题,如果您无法修复它,则必须拒绝错误处理程序中的承诺。请参阅 angular documentation 中的这段摘录:

When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.

promiseB = promiseA.then(function(result) {
  // success: do something and resolve promiseB
  //          with the old or a new result
  return result;
}, function(reason) {
  // error: handle the error if possible and
  //        resolve promiseB with newPromiseOrValue,
  //        otherwise forward the rejection to promiseB
  if (canHandle(reason)) {
   // handle the error and recover
   return newPromiseOrValue;
  }
  return $q.reject(reason);
});

对于您的情况,这仅意味着您必须按如下方式修改错误处理程序(确保 $q 可用):

function restangularError(response) {
    $log.error("Error with status code", response.status);
    return $q.reject(response);
}