4.8 Callback Errors

Current apps have few big flaws.
If we try to give an address that does not exist, such error message will pop up.

console.log(`Address: ${body.results[0].formatted_address}`);
TypeError: Cannot read property 'formatted_address' of undefined
at Request.request [as _callback] (C:\Users\x85gao\Desktop\4\app.js:22:45)
at Request.self.callback (C:\Users\x85gao\Desktop\4\node_modules\request\request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (C:\Users\x85gao\Desktop\4\node_modules\request\request.js:1157:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (C:\Users\x85gao\Desktop\4\node_modules\request\request.js:1079:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)

We should make an error callback to handle these types of errors:

if (err) { // err object only checks machine errors
console.log("Unable to connect to Google Servers!");
} else if (body.status === 'ZERO_RESULTS') { // when address not found
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(`Longtitude: ${body.results[0].geometry.location.lng}`);

Now instead our program crashing, we get the message printed on the screen.

$ node app.js -a 0000
Unable to find that address.