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.
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.
来源:https://stackoverflow.com/questions/26528688/grape-error-handling-strategy