Skip to content

Instantly share code, notes, and snippets.

@thogg4
Created January 4, 2013 04:30
Show Gist options
  • Save thogg4/4449932 to your computer and use it in GitHub Desktop.
Save thogg4/4449932 to your computer and use it in GitHub Desktop.
rack middleware to catch exceptions
module Rack
class ExceptCatcher
def initialize(app, mailer)
@app = app
@mailer = mailer
@ignore = [404]
@hash_blacklist = %w(rack.session.options)
end
def call(env)
@env = env
begin
@status, @headers, @response = @app.call(@env)
rescue Exception => e
send_email(build_hash(e, @env))
raise
end
if framework_exception
send_email(build_hash(framework_exception, @env))
end
[@status, @headers, @response]
end
def framework_exception
@env['sinatra.error']
end
def build_hash(e, env)
hash = {
name: e.to_s,
timestamp: Time.now,
backtrace: e.backtrace,
backtrace_summary: e.backtrace[0..3],
status: @status,
env: build_env
}
end
def build_env
env = []
@env.each do |key, value|
next if @hash_blacklist.include?(key)
env << {'key' => key.to_s, 'value' => value.to_s}
end
env
end
def ignore_status(status)
@ignore.include?(status)
end
def send_email(hash)
hash.merge!({
to: 'someemail'
})
@mailer.mail(hash) unless ignore_status(hash[:status])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment