Angular:在找不到文件时捕获404错误

时间:2017-11-14 12:49:40

标签: angularjs promise

在我的Ionic项目中,我正在创建一个函数来查明文件是否存在于本地。我创建了以下函数:

$rootScope.eventFieldTemplateExists = function(field) {
    //var templateUrl = 'views/fields/' + field.name + '.html';
    var templateUrl = 'views/fields/testfile.html';


    $http.head(templateUrl).then(function(res) {
      console.log("success");
      console.log(res);
    })
    .catch(function(err) {
      console.log("catch");
      console.log(err);
    });

    return true;
};

文件testfile.html不存在。当我输入一个存在的文件时,上面的工作正常,但是当文件不存在时我仍然会收到控制台错误:

HEAD http://localhost:9000/views/fields/testfile.html 404 (Not Found)
catch
{data: "", status: 404, config: {…}, statusText: "Not Found", headers: ƒ}

有没有办法抑制错误?我希望.catch会抑制它,但显然它没有。

2 个答案:

答案 0 :(得分:0)

状态为404的响应将调用promise的拒绝处理程序,这是预期的行为,但是您的代码不包含它,因此控制将进入.catch

加入拒绝处理程序并解决回复.when

$http.head(templateUrl).then(function(res) {
    // this will run for status 2xx
    console.log("success");
    console.log(res);
}, function(response) {
    // this will run for status 4xx, 5xx, etc..
    if (response.status === 404) {
        return $q.when("404: file not found, but it's ok")
    }
    return $q.reject(response);
})   
.catch(function(err) {
  console.log("catch");
  console.log(err);
});

答案 1 :(得分:0)

您可以使用then()的第二个参数捕获$http.head(templateUrl).then(function(res) { console.log("success"); console.log(res); }, function(err) { console.log("catch"); console.log(err); }) 请求中的所有错误。

$http.head

AngularJs $http.head('/someUrl', config).then(successCallback, errorCallback); 的工作原理如下:

SaveFileDialog

Documentation on $http