如何在发出 fetch api 请求时捕获错误?

How to catch the error when making fetch api request?

我正在使用 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 内部服务器错误 仍然重定向到 /mainpage 并且无法识别错误。我该如何解决这个问题?

fetch 请求从服务器返回错误代码时,承诺的 catch 不会执行,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.statusresponse.statusText.

中找到有关此错误的信息

如果您正在使用 async await,则不必像处理 promise 一样链接 .thens。

我调整了您的代码并将其包装在 try/catch 中,try/catch 错误将处理来自无响应的错误,但是您需要检查服务器响应本身是否有错误

async loginUser() {

    try {
        let response = await this._service.LoginUser(this.user)

        // Check your response for error this may not be response.error
        if (response.error) {
            // Handle error
            alert(error)
        } else {
            // Navigate on success
            this._router.navigate(['/mainpage'])
        }
    } catch (err) {
        alert(err)
    }
}