We’ve been using Grape to provide a RESTful API. Grape is a micro-framework for Ruby that makes it really easy.
I’ve recently had to deal with code that raises exceptions in a bunch of unpredictable places. This causes Rails to produce an HTML error page, including when making JSON API calls. We want to have some control of this and wrap all calls to return an error message or maybe even a JSON error message. To do so we’ll write the following exception handler. It traps all exceptions in a rescue block and re-throws a specific :error that Grape expects.
This can be injected into the middleware stack, a construct I find quite elegant.
To be good citizens we’ll write an RSpec test, heavily inspired by Grape’s specs.
I couldn’t figure out how to wrap it up to return JSON, I keep having to raise an :error to abort all subsequent middleware processors. Maybe someone can suggest a solution or a better approach altogether?