Last Updated: February 25, 2016
·
969
· gus

Intercepting exceptions for better logging

Dealing with logs in Ruby applications can sometimes be a pain in the butt, if you happen to be lucky enough to be running Rails along with any of the awesome error tracking apps out there you might not have ran into these kind of problems.

If you are not that fortunate you might have wanted to get more information out of your exceptions. One way of doing so if by leveraging rack's awesome middleware.

class ExceptionInterceptor
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)

    if status == 500
      msg = {
        'REQUEST_URI'    => env['REQUEST_URI'],
        'REQUEST_METHOD' => env['REQUEST_METHOD'],
        'action_dispatch.request.parameters' => env['action_dispatch.request.parameters']
      }.to_s

      logger.fatal msg
    end

    [status, headers, body]
  end
end

You can then insert the middleware somewhere in the stack, in this case we want it to intercept ActionDispatch's exceptions.

config.middleware.insert_before ActionDispatch::ShowExceptions, ExceptionInterceptor

Writing middleware is easy and it can help separating concerns and keeping your code clean and simple.