JavaScript Node.js Basics Handling Errors in Node Handling Status Code Errors

Amandeep Pasricha
Amandeep Pasricha
14,931 Points

Why do we need an if statement for the status code if we are already applying a try and catch block to the code?

If we already have a try and catch block for errors, why do we need to add one for responses?

Wouldn't the catch code catch the error and then we would output the error.message.

What's the point of the try and catch then if we need an if statement for response errors?

1 Answer

Tobias Edwards
Tobias Edwards
14,256 Points

Before the if-statement for the status code, we have:

const getProfile = username => {
  try {
    https
      .get(`https://teamtreehouse.com/${username}.json`, response => {
        let body = ''

        response.on('data', data => {
          body += data.toString()
        })

        response.on('end', () => {
          try {
            const profile = JSON.parse(body)
            console.log(
              printMessage(
                profile.profile_name,
                profile.badges.length,
                profile.points.JavaScript
              )
            )
          } catch (e) {
            console.error('Invalid username')
          }
        })
      })
      .on('error', e => {
        printError(e)
      })
  } catch (e) {
    printError(e)
  }
}
  • The first try-catch block will catch errors in visiting the URL e.g. problems with the URL
  • The second try-catch block within the response.on block will catch errors thrown by JSON.parse()

Why have an if-else condition to check for status codes? e.g. suppose we enter a valid URL, and pass a valid username. But, the treehouse website is down, and so will throw a 500 error! Our code will catch the error and say the problem is that the data couldn't be parsed. This is wrong - the actual error that should have been outputted is "500 error".

I had the same question as you, and this is what I thought of? Please correct me if I'm wrong.

TLDR; The if-else condition is needed to catch and display the appropriate error message.