我的错误消息未返回,仅显示默认错误消息

My error message is not being returned, the default error message is only being displayed

提问人:Deveshi Singh 提问时间:11/2/2023 更新时间:11/2/2023 访问量:18

问:

在下面的代码中,当我捕获错误时,不会返回 getJSON 中定义的错误消息,仅返回默认值。我该如何解决这个问题,这是输出

const getJSON=function(url,errMsg='something went wrong'){
  return fetch(url)
  .then((res)=>{
    if(!res.ok){
      throw new Error(`${errMsg} ${res.status}`);
    }
    return res.json();
  })
}

const getCountryData=function(country){
  getJSON(`https://restcountries.com/v3.1/name/${country}`,'country not found')
  .then((data)=>{
    renderCountry(data[0]);
    const neighbor=data[0].borders[0];
    if(!neighbor)throw new Error('no neighbor found');
    return getJSON(`https://restcountries.com/v3.1/alpha/${neighbor}`,'country not found')
  })
  .then((data)=>{
    renderCountry(data[0],'neighbour');
  })
  .catch(err=>{
    console.log(err);
    renderError(`oops ${err} Try again`);
  })
  .finally(()=>{
    countriesContainer.style.opacity = 1;
  })
}

btn.addEventListener('click',function(){
  getCountryData('australia');
});

我遵循了通常的语法,预期的输出应该是“哎呀,找不到邻居,再试一次”

JavaScript 调试

评论

0赞 htor 11/2/2023
嗨,Deveshi!链接的错误消息表明您正在尝试读取某个对象的索引。我怀疑要么是 ,要么是 的某个值。0undefineddatadata[0].bordersundefinedcountry
0赞 Armali 11/2/2023
HTOR 是对的,undefined 是 .data[0].borders

答: 暂无答案