Log All 400 Errors in Rails 5

There are a lot of ways to do this, but I searched for the title of this post and got few results.

One solution is to write some custom middleware. (WARNING: if you’re using Puma, make sure your middleware is threadsafe).

Here’s a great guide: https://lmiller1990.github.io/electic/posts/custom_middleware_in_rails_5.html

You can specify different behavior based on status codes:

  def call(env)
    @status, @headers, @body = @app.call(env)
    if @status == 400
      # do something here
    end
    [@status, @headers, @body]
  end

And you’ll need to add your middleware to the configs:

# config/environments/development.rb
config.middleware.insert_before ActionDispatch::ShowExceptions, MyMiddleware

Comments are closed.

%d bloggers like this: