Grape Error Handling Strategy?

I use Grape and Rails to create a REST API. I have basic architecture in place, and I am looking for places for "clean" things. One such place is error handling / handling.

I am currently saving errors in the root.rb file (GRAPE :: API base class) for the entire API. I will format them and then send the error back through rack_response. Everything works, but the root.rb file gets a little bloated with all errors fixed, and some of them have special parsing that needs to be done. I was wondering if someone had developed a good strategy for handling errors so that you could move it to your own module and leave the root .rb (base class of GRAPE :: API) rather meager.

I would really like to create an error handling module and define methods for each type of error, for example ...

module API module ErrorHandler def record_not_found rack_response API::Utils::ApiErrors.new({type: e.class.name, message: 'Record not found'}).to_json, 404 end end end 

Then in root.rb do something like this

 module API class Root < Grape::API prefix 'api' format :json helpers API::ErrorHandler rescue_from ActiveRecord::RecordNotFound, with: :record_not_found # Use the helper method as the handler for this error end end 

Has anyone done something like this? I have tried various variations of the above strategy, but I cannot get anything to work.

+8
rest ruby ruby-on-rails grape grape-entity
source share
1 answer

I came to the next solution / strategy ...

I moved all the errors to my own module, as shown below.

 module API module Errors extend ActiveSupport::Concern included do rescue_from :all do |e| rack_response API::Utils::ApiErrors.new({type: e.class.name, message: e.message}).to_json, 500 end . . . end end 

Then I just include errors in my base class GRAPE :: API

 module API class Root < Grape::API include API::Errors prefix 'api' format :json helpers API::Utils::Helpers::IndexHelpers helpers API::Utils::Helpers::WardenHelpers helpers API::Utils::Helpers::RecordHelpers . . . end end 

After a lot of experimentation and many other attempts, it doesn’t work, I think this is a great solution, and my base class GRAPE :: API remains rather meager. I am still very open to any other approaches that people may have.

+5
source share

All Articles