Last Updated: February 25, 2016
· 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

  def call(env)
    status, headers, body =

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

      logger.fatal msg

    [status, headers, body]

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.