Angular JS将数据传递给$ http全局错误处理程序

时间:2015-11-26 04:56:57

标签: angularjs

我有$ http请求的全局错误处理函数。

var errorHandler = function (err) {
    // log the error
    return {status: err.status, data: {result: -1}}
}

var get = function (url) {
    var i = 1      // I have a temp variable here, and want to pass it to errorHandler

    return $http({
        method: 'GET',
        url: ***,
        timeout: 5000,
    }).then(function (response) {
        // do some thing
        return response
    }, errorHandler)
}

如何将变量i传递给errorHandler? 我知道我可以这样做:

var get = function (url) {
    var i = 1      // I have a temp variable here, and want to pass it to errorHandler
return $http({
    method: 'GET',
    url: ***,
    timeout: 5000,
}).then(function (response) {
    // do some thing
    return response
}, function (err) {
    // log the error
    console.log('i', i)   // access i
    return {status: err.status, data: {result: -1}}
    })
}

但如果我想使用全局errorHandler,我该怎么办?

==============

更新

根据Leandro Zubrezki的回答,我们可以这样做:

var errorHandler = function (err, i) {
    // log the error
    return {status: err.status, data: {result: -1}}
}

var get = function (url) {
    var i = 1      // I have a temp variable here, and want to pass it to errorHandler

    return $http({
        method: 'GET',
        url: ***,
        timeout: 5000,
    }).then(function (response) {
        // do some thing
        return response
    }, function(error){
        errorHandler(error, i)
    })
}

这是来自新手的愚蠢问题。 :)

1 个答案:

答案 0 :(得分:2)

这样做:

function(error) {
     errorHandler(error, i);
}