Nested try/catch or alternative

Which one of these snippets (or a different approach) would you consider better?

document.getElementById('drive').addEventListener('click', async () => {
  let driverOptions = {}
  
  /*----------  Create request.body with Geolocation and form data  ----------*/
  try {
    const position = await getLocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0
    })
    driverOptions = {
      name: document.querySelector('[name="fullName"]').value,
      email: document.querySelector('[name="email"]').value,
      tractor: document.querySelector('[name="tractor"]').value,
      geometry: {
        type: 'Point',
        coordinates: [position.coords.longitude, position.coords.latitude]
      }
    }
  } catch (err) {
    console.log(err)
    return
  }

  /*----------  POST data to API  ----------*/
  try {
    let res = await fetch('/api/drivers', {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(driverOptions)
    })
    let data = await res.json()
    console.log(data)
  } catch (err) {
    console.log(err)
  }
}, false)

…or

document.getElementById('drive').addEventListener('click', async () => {
  try {
    const position = await getLocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0
    })
    const driverOptions = {
      name: document.querySelector('[name="fullName"]').value,
      email: document.querySelector('[name="email"]').value,
      tractor: document.querySelector('[name="tractor"]').value,
      geometry: {
        type: 'Point',
        coordinates: [position.coords.longitude, position.coords.latitude]
      }
    }

    try {
      let res = await fetch('/api/drivers', {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(driverOptions)
      })
      let data = await res.json()
      console.log(data)
    } catch (err) {
      // API database error
      console.log(err)
    }
  } catch (err) {
    // Geolocation error
    console.log(err)
  }
}, false)

They both work, but I’m not entirely sure which is better. I like the first because it doesn’t have a try/catch nested inside another try/catch, but to do that it needs an extra variable and a little more code. What would you do?

From the depth of my inexperience i vote the first option!
I mean, it’s way cleaner than the second one: the only significant difference I can see is that the first option keep different operations separated.
To add few lines of code to make the code much clean / clear is definitely a good choice imho^^

1 Like