【问题标题】:How to handle error in 'get' request in runtime?如何在运行时处理“get”请求中的错误?
【发布时间】:2014-12-03 05:18:14
【问题描述】:

我在 AngularJS 中使用 $http 服务向 url 发出 get 请求

$http.get(url).
    success(function(data){
     ... // store data in localStorage
    }).
    error(function(){
     ... // get data from localStorage
    });

当服务器关闭时,上面的“错误”条件会被执行,但应用程序会停止。我希望申请继续处理。因此,如果出现错误,应用程序应该从 localStorage 获取数据。

我尝试使用 try 和 catch 处理异常,但应用程序仍然停止。

try{
    $http.get(url).
    ... // store data in localStorage
 }
 catch(ex){
  ...  // get data from localStorage
 }

尝试 try catch 的原因是,在一个简单的 try catch 块中,即使抛出异常也可以继续执行。

我想知道如何解决这个问题。

【问题讨论】:

  • 我认为你应该把它放在你的后端。
  • 如果你得到一个 http 错误,那么应用程序不应该停止。你能指定你得到的异常吗?
  • @user1537766 不是 http 错误。我得到“GET net::ERR_CONNECTION_REFUSED”

标签: angularjs error-handling get


【解决方案1】:

$http.get(url)。 成功(功能(数据){ ... // 将数据存储在 localStorage })。 错误(函数(){ if (error.status == 500 || error.status == 406) { // 从本地存储中获取数据 } } });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多