I am using Grape and Rails to create a REST API. I have the basic architecture in place and I am looking for places to 'clean' things up. One of those places is the error handling/processing.
I am currently rescuing errors in the root.rb (GRAPE::API base class) file for the whole API. I format them and then send the error back via rack_response. Everything works find but the root.rb file is getting a bit bloated with all the errors being rescued and some of them have special parsing that needs to be done. I was wondering if anyone has developed a good strategy for error handling so that it can be moved out into it's own module and leave the root.rb (GRAPE::API base class) fairly lean.
I would really like to create a error processing 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 the root.rb file 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 been trying various flavors of the above strategy but I can't seem to get anything work.
Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs.
The grape-swagger gem provides an autogenerated documentation for your Grape API. The generated documentation is Swagger-compliant, meaning it can easily be discovered in Swagger UI. You should be able to point the petstore demo to your API. This screenshot is based on the Hussars sample app.
I've come to the following solution/strategy...
I moved all error rescuing to its own module like the following
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 simply include the errors in my base GRAPE::API class
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 a lot of other attempts not working, I think this is a fine solution and my base GRAPE::API class remains pretty lean. I am still very open to any other approaches people might have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With