Skip to content

Instantly share code, notes, and snippets.

@steve9001
Created December 7, 2011 16:18
Show Gist options
  • Save steve9001/1443408 to your computer and use it in GitHub Desktop.
Save steve9001/1443408 to your computer and use it in GitHub Desktop.
Rails middleware to provide information about errors during requests
module MyApp
class Application < Rails::Application
if Rails.env == 'test'
require 'diagnostic'
config.middleware.use(MyApp::DiagnosticMiddleware)
end
end
end
module MyApp
class DiagnosticMiddleware
FILENAME = 'diagnostic.txt'
def initialize(app)
@app = app
end
def call(env)
return @app.call(env)
rescue StandardError => e
trace = e.backtrace.select{ |l|l.start_with?(Rails.root.to_s) }.join("\n ")
msg = "#{e.class}\n#{e.message}\n#{trace}\n"
File.open(FILENAME, 'a') { |f| f.write msg }
raise e
end
end
end
@Paxa
Copy link

Paxa commented Mar 16, 2015

Thanks, very useful. I just print to stdout:

module MyApp
  class DiagnosticMiddleware

    def initialize(app)
      @app = app
    end

    def call(env)
      return @app.call(env)
    rescue StandardError => error
      puts error.message
      puts error.backtrace
      raise error
    end
  end
end

@jerefrer
Copy link

Proved helpful in a case of "Internal server error" while running a spec which did not provide much detail either on the page or in the test log file.

Thanks a bunch !

@grauschnabel
Copy link

the same here, i would also like to have it as a spec, so it does not work for me.

@aterletskiy
Copy link

It didn't work for me until I changed it to rescue Exception instead of StandardError.

@davidmles
Copy link

application.rb should be:

if Rails.env == 'test'
  require File.expand_path('../diagnostic', __FILE__)
  config.middleware.use(MyApp::DiagnosticMiddleware)
end

@mcmire
Copy link

mcmire commented Apr 24, 2017

I happened to handle this a little bit differently -- by detecting RoutingErrors on image paths: https://gist.github.com/mcmire/68cd9c74ba765a2d5dfb14abf58409aa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment