Rescue your Ruby Application

Moving into the second module of my coding bootcamp experience, last week we ended the first module building our first command line applications. After exchanging ideas back and forth with my partner, we came to a conclusion that we were gonna build a weather application. Using a weather API, a user would sign in and search any desired location which would fetch live weather updates from our API.

Building out our application was a tremendous learning experience, being able to put together all of the skills we had attained through the labs and lectures over the past 2+ weeks. Our program was coming together and beginning to execute smoothly. However, we had a major problem. When a user would type in a location with a typo or that our API wouldn’t recognize, our program immediately broke. We had to figure out a solution that would keep the continuous flow of the application.

We began browsing the web on ways to save our application using some sort of error handling. We came across begin…rescue.

( screenshot from our project )

The code you add in between “begin” and “rescue” is where you think an exception might occur. If an exception occurs, the rescue block will execute.

Through reading the standard error messages we kept getting from ruby, we knew that our API would return a 404 exception when it didn’t recognize a search. After a few attempts trying the implement begin…rescue, we had our program loop back up to a get_user_input method which would prompt the user again for input. This in turn saved our application. Our API search method was fail proof.

Other ways we can use rescue is during an iteration:

* using rescue during itteration *

For example, if we had had a method that would take an array of numbers and divide each number by itself, that would work. But what happens if we try dividing 0 by itself? Here we can implement our handy rescue command to handle the error well get, and continue the flow of the program.

In addition, there are other ways to utilize this type of error handling. One way to do this is with the keyword “retry”. Retry is implemented in the rescue block which will re-execute the task from the begin block.

* ruby rescuing our app *

The rescue block in Ruby is very powerful. It’s vastly easier to use than error codes. Rescue lets you create more robust solutions by providing a simple way to deal with common errors that might occur in your program.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store