The first thing we'll do is add an if statement as shown below, checking if the error object exists:
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json: true
}, (error, response, body) => {
if (error) {
}
This will run the code inside of our code block if the error object exists, if it doesn't fine, we'll move on into the next else if statement, if there is any.
If there is an error, all we'll do is add a console.log and a message to the screen, something like Unable to connect to Google servers:
if (error) {
console.log('Unable to connect Google servers.');
}
This will let the user know that we were unable to connect to the user servers, not that something went wrong with their data, like the address was invalid. This is what be inside of the error object.
Now the next thing that we'll do is add an else if statement, and inside of the condition we'll check the status property. If the status property is ZERO_RESULTS, which it was for the zip code 000000, we want to do something other than trying to print the address. Inside of our conditional in Atom, we can check that using the following statement:
if (error) {
console.log('Unable to connect Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
}
If that's the case, we'll print a different message, other than Unable to connect Google servers, for this one we can use console.log to print Unable to find that address.:
if (error) {
console.log('Unable to connect Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
console.log('Unable to find that address.');
}
This lets the user know that it wasn't a problem with the connection, we were just unable to find the address they provided, and they should try with something else.
Now we have error handling for those system errors, like being unable to connect to the Google servers, and for errors with the input, in this case we're unable to find a location for that address, and this is fantastic, we have both of our errors handled.
In our case, if the status is ZERO_RESULTS, we know the request failed and we can act accordingly. Inside of our app, now we'll add our last else if clause, if things went well.