2

I'm using fetch on https://www.googleapis.com/books/v1/volumes?q=wiedzmin . If you go to this link you can see that it is not any volumeInfo.authors in 9th object (from line 545 to 602). It gives me an error:

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

I would like to make a logic like "if there is an error return "No value found" , and code execution will go further.

my piece of code:

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(', '))
          }

      })
SuperStar518
  • 2,814
  • 2
  • 20
  • 35
Baldini
  • 97
  • 1
  • 4

1 Answers1

4

You can try check x.items[i].volumeInfo.authors if it is undefined then default empty array let the error would not occur:

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(', '))
      }
    })

Or if you want ignore x.items[i].volumeInfo.authors is undefined, You still can use 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')
        }
      }
    })
Clark
  • 305
  • 1
  • 8