【问题标题】:How to service error if there is not specific key, but it should be如果没有特定的密钥,如何服务错误,但应该是
【发布时间】:2019-10-19 16:47:04
【问题描述】:

我在 https://www.googleapis.com/books/v1/volumes?q=wiedzmin 上使用 fetch。如果您转到此链接,您会看到它不是第 9 个对象中的任何 volumeInfo.authors(从第 545 行到第 602 行)。 它给了我一个错误:

Uncaught (in promise) TypeError: Cannot read property 'join' of undefined

我想做一个类似“如果有错误返回“No value found”的逻辑,代码执行会更进一步。

我的一段代码:

fetch("https://www.googleapis.com/books/v1/volumes?q=wiedzmin")
    .then(resp => resp.json())
    .then(x => {

      console.log('AUTHORS: ')
        for(let i=0; i <= x.items.length - 1; i++){
          console.log(x.items[i].volumeInfo.authors.join(', '))
          }

      })

【问题讨论】:

    标签: javascript object promise fetch


    【解决方案1】:

    您可以尝试检查x.items[i].volumeInfo.authors,如果是undefined,则默认空数组让错误不会发生:

    fetch("https://www.googleapis.com/books/v1/volumes?q=wiedzmin")
        .then(resp => resp.json())
        .then(x => {
          console.log('AUTHORS: ')
          for(let i=0; i <= x.items.length - 1; i++){
              console.log((x.items[i].volumeInfo.authors || []).join(', '))
          }
        })
    

    或者如果你想忽略x.items[i].volumeInfo.authors是undefined,你仍然可以使用if:

    fetch("https://www.googleapis.com/books/v1/volumes?q=wiedzmin")
        .then(resp => resp.json())
        .then(x => {
          console.log('AUTHORS: ')
          for(let i=0; i <= x.items.length - 1; i++){
            if(x.items[i].volumeInfo.authors) {
              console.log(x.items[i].volumeInfo.authors.join(', '))
            } else {
              console.log('No value found')
            }
          }
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 2017-05-27
      • 2017-01-29
      • 2011-04-14
      相关资源
      最近更新 更多