What happens if you try to draw driving directions across the sea?
If you do that, Google Maps will return an error.
Hereโs a list of possible errors (from the API):
| Status | Explanation |
|---|---|
INVALID_REQUEST |
Request was invalid |
MAX_WAYPOINTS_EXCEEDED |
Too many waypoints in the request |
NOT_FOUND |
At least one origin, destination, or waypoint cannot be geocoded |
OVER_QUERY_LIMIT |
Too many requests in a short period of time |
REQUEST_DENIED |
Not allowed to use directions service |
UNKNOWN_ERROR |
Server error |
ZERO_RESULTS |
Cannot find a route between origin and destination. |
Googleโs Directions Service doesnโt return a friendly error message. It only returns the status. We need to write the error message ourselves.
Letโs put the error messages into an object.
const errors = { INVALID_REQUEST: 'Invalid request', MAX_WAYPOINTS_EXCEEDED: 'Maximum of 8 waypoints allowed', NOT_FOUND: 'At least one location cannot be geocoded', OVER_QUERY_LIMIT: 'You sent too many requests in a short time. Slow down!', UNKNOWN_ERROR: 'An error happened on the server. Please try again later', ZERO_RESULTS: 'Cannot find route between origin and destination',}We can extract the error message with result.status:
searchPanel.addEventListener('submit', event => { // ... getDirections(request) .then(/*...*/) .catch(result => { const errors = { INVALID_REQUEST: 'Invalid request', MAX_WAYPOINTS_EXCEEDED: 'Maximum of 8 waypoints allowed', NOT_FOUND: 'At least one location cannot be geocoded', OVER_QUERY_LIMIT: 'You sent too many requests in a short time. Slow down!', UNKNOWN_ERROR: 'An error happened on the server. Please try again later', ZERO_RESULTS: 'Cannot find route between origin and destination', } const message = errors[result.status] })})We want to show this error message in the DOM. For this, weโll create a <div> with a class called .search-panel__error.
<div class="search-panel__body"> <div class="search-panel__error"></div> <!-- ... --></div>In the catch call, we will look for the error div and create the error message.
searchPanel.addEventListener('submit', event => { // ... getDirections(request) .then(/*...*/) .catch(result => { // ... const errorDiv = searchPanel.querySelector('.search-panel__error') errorDiv.textContent = message })})Clearing errors
Finally, we must clear the errors when a user tries to search for directions.
searchPanel.addEventListener('submit', event => { // ... const errorDiv = searchPanel.querySelector('.search-panel__error') errorDiv.textContent = '' // ...})Thatโs it !
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson