簡體   English   中英

處理 javascript 中的 HTTP 500 獲取捕獲

[英]Handling HTTP 500 in javascript fetch catch

我正在使用 API,如果發生內部服務器錯誤,則錯誤的詳細信息將以 JSON 格式返回。

目前,我有以下代碼可以處理成功的響應,但在 HTTP 500 響應的情況下,狀態文本會記錄在控制台中:

function checkStatus(response) {
    if (!response.ok) {
        throw new Error(response.statusText);
    }
    return response;
}

fetch("/api/url")
    .then(checkStatus)
    .then(response => response.json())
    .then(data => {
        // process success JSON here
    })
    .catch(err => {
        console.log(err);
    });

我將如何處理在 HTTP 500 響應中返回的 JSON,以便可以在document.getElementById(id).innerHTML分配中使用這些屬性?

即使出現錯誤 500,響應中包含的 json 始終位於response.json()中。

在您的示例中,您拋出的錯誤僅包含statusText

你可以改為這樣做:

function checkStatus(response) {
  if (!response.ok) {
    response.json().then((jsonError: any) => {
      // your code to handle the json, for example:
      if (error.status === 500) {
            throw new HttpError('Something went wrong', jsonError);
        }
    }
  }
  return response;
}

例如,您可以創建一個新的 class 錯誤,其中包含與您的jsonError對應的屬性:

export class HttpError extends Error {
    public jsonError: any;
    constructor(error: Error, jsonError: any) {
        super(error.message);
        this.jsonError = jsonError;
    }
}

然后你可以在你的catch()方法中使用jsonError屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM