Last active
January 28, 2016 21:40
-
-
Save arempe93/6b6bd9cb29c7c653f9e7 to your computer and use it in GitHub Desktop.
Grape Middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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