Now we want to add the else if clause checking if the body.status property equals OK. If it does, we can go ahead and run these three lines inside of the code block:
console.log(`Address: ${body.results[0].formatted_address}`);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longitude: ${body.results[0].geometry.location.lng}`);
});
If it doesn't, these lines shouldn't run because the code block will not execute. Then we'll test things out inside of the Terminal, try to fetch the address of 00000, and make sure that instead of the program crashing we get our error message printing to the screen. Then we go ahead and mess up the URL in the app by removing some of the important characters, and make sure this time we get the Unable to connect to the Google servers. message. And last we'll see what happens when we enter a valid address, and make sure our three console.log statements still execute.
To get started we'll add that else if statement, and inside of the condition we'll check if body.status is OK:
if (error) {
console.log('Unable to connect Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
console.log('Unable to find that address.');
} else if (body.status === 'OK') {
}
If it is OK, then we'll simply take the three console.log lines (shown in the previous code block) and move them in the else if condition. If it is OK, we'll run these three console.log statements:
if (error) {
console.log('Unable to connect Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
console.log('Unable to find that address.');
} else if (body.status === 'OK') {
console.log(`Address: ${body.results[0].formatted_address}`);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longitude: ${body.results[0].geometry.location.lng}`);
}
Now we have a request that handles errors really well. If anything goes wrong we have a special message for it, and if things go right we print exactly what the user expects, the address, the latitude, and the longitude. Next we'll test this.