javascript - 获取 api 请求时如何捕获错误?

标签 javascript angular typescript fetch fetch-api

这个问题在这里已经有了答案:





How to handle HTTP code 4xx responses in fetch api

(4 个回答)



Handle a 500 response with the fetch api

(1 个回答)



try..catch not catching async/await errors

(1 个回答)


1年前关闭。




我正在使用 fetch api 发送请求并根据结果正确或包含错误进行操作。
我的服务代码:

LoginUser(user: User) {
    return fetch("http://localhost:8080/login", {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(user)
    });
  }
和我的then-catch调用上述代码的代码是:
async loginUser() {
  let response = await this._service.LoginUser(this.user)
  .then(response => {return response.json()})
  .then(response => {this._router.navigate(['/mainpage'])})
  .catch(error => {alert(error)});
 }
响应是否带有代码 500 Internal Server Error 仍然重定向到 /mainpage并且不识别错误。我该如何解决这个问题?

最佳答案

当一个 fetch请求从服务器返回一个错误代码 catch的 promise 未执行,then是。 catch仅在网络故障时执行。见 the fetch docs :

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.


你需要做的是,在你的 then , 检查 response.ok .如果 response.ok == false ,然后请求返回错误。您可以在 response.status 中找到有关此错误的信息。和 response.statusText .

关于javascript - 获取 api 请求时如何捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63103029/

相关文章:

javascript - 在每个页面上 react 路由器加载路由

Javascript 按钮监听器触发一次?

javascript - 为什么我的 Javascript for 循环是连接数字而不是相加?

angular - angular 2 和纯 javascript 之间的通信

typescript 类型转换

javascript - context.beginPath() 不是一个函数——为什么?

angular - ng2-select 中的数据绑定(bind)失败

angular - 从选项卡转到根页面

javascript - typescript 新手,我对 AMD 的理解是否正确?

jquery - 如何将 jQuery 的 $.post() 方法与 async/await 和 typescript 一起使用