要捕獲JSON響應中的錯誤,可以使用try/catch語句來捕獲異常,并從JSON響應中提取錯誤信息。例如:
try {
// Make the request
let response = await fetch('/api/endpoint');
let json = await response.json();
// Check for errors
if (json.error) {
throw new Error(json.error);
}
} catch (err) {
// Handle the error
console.error(err);
}