Skip to content

Instantly share code, notes, and snippets.

@arempe93
Last active January 28, 2016 21:40
Show Gist options
  • Save arempe93/6b6bd9cb29c7c653f9e7 to your computer and use it in GitHub Desktop.
Save arempe93/6b6bd9cb29c7c653f9e7 to your computer and use it in GitHub Desktop.
Grape Middlewares
class APILogger < Grape::Middleware::Base
def before
request_method = env['REQUEST_METHOD']
Rails.logger.info "REQUEST METHOD:\t#{request_method}"
Rails.logger.info "REQUEST PATH:\t#{env['REQUEST_PATH']}"
Rails.logger.info "QUERY STRING:\t#{env['QUERY_STRING']}"
Rails.logger.info "POST PARAMS:\t#{env['rack.request.form_hash']}" if request_method == 'POST'
end
end
class ErrorHandler < Grape::Middleware::Base
def call!(env)
# capture env
@env = env
begin
# make api call
@app.call @env
rescue => e
Rails.logger.error "API ERROR: #{e.message}"
Rails.logger.error "API ERROR: #{e.backtrace.join("\n\t")}"
# rescue from uncaught exceptions
catch_error e
end
end
private
def catch_error(e)
response = {
response_code: 500,
response_text: 'Internal Server Error',
error_code: '500',
error_text: e.message
}
[ 500, { 'Content-Type' => 'application/json' }, [ response.to_json ] ]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment