Why do exceptions happen all the time in Ruby and Rails applications?

“Exception” sure is a funny name for something that Ruby and Rails programmers deal with all… day… long. Because of that, you need to master the what, how, when, and why of using exceptions.

Read on to learn all about using exceptions effectively in Ruby…

When should you use exceptions?

Things go wrong in software all the time – sometimes the user enters bad data, and sometimes a developer uses a library incorrectly. How do you decide when it’s the right time to use an exception? Distinguish user errors from developer errors, and you’ll be on your way to writing robust code that uses exceptions effectively.

Help! There’s HTML in my JSON API!

You’ve built a shiny new API with Rails 5, but error pages in development mode throw you off – they’re all in HTML, but your frontend expects JSON! If you could get the errors in JSON, then you could examine them in your browser console… Rails 5 has you covered with its debug_exception_response_format option.

You want a consistent test suite – no exceptions!

There’s one kind of exception that everybody hates – inconsistent test failures. Your test suite needs to produce consistent results for it to give you confidence. Learn how randomness, database ordering, global modification, and time are throwing off your test suite.

Ruby’s Timeout library can cause major headaches

When your code calls an external service, you usually want to provide it with a timeout so your application doesn’t hang forever. Ruby’s timeout library comes in handy here, but sometimes it causes problems that are really tough to track down. At least now you know what to be aware of…

Can a subclass do less than its parent class?

Sometimes when you inherit from a class, you get more than you bargained for… you get a big interface and an entire implementation when you really just want to implement a few methods. Be clear on when you want to borrow an implementation, and when you want to share an interface.

Ask your exceptional questions below!

Do you have questions about exceptions in Ruby and Rails? Ask them in the comments below, or help other readers!

"How do I become a better Ruby developer?"

Blogs, books, and bootcamps all promise to make you a better Ruby developer, but end up confusing you more.

What if you had step-by-step instructions on how to become a better Ruby developer?

Enter your name and email below and I’ll show you how to...

  • get better at Ruby in just five minutes each day
  • use testing, OOP, and refactoring to write professional-level Ruby
  • identify and learn new programming skills quickly