in Railscasts, Uncategorized

Railscast 053 Handling Exceptions

GitHub Repo

Heroku App

Rack Middleware

I created this episode in order to understand how rack middleware works. There was really only one line that pertained rack middleware

config.exceptions_app = self.routes

This line is a little hack to define the Rails routes as the rack middleware app that should handle exceptions. From the routes we can then match the status error in a route and map to a controller action.

Route

match '(errors)/:status', to: 'errors#show', constraints: {status: /\d{3}/}, via: :get

This route line provided me with a few lessons. the () in a route is an optional route. A route like products/:id(/:type/:year) would match a route for the product from the id and optional add the type or year params if specified.

The constraints part about further specifies what is acceptable in a route and what is not acceptable. Here we are using regex to constrain the status param to only be 3 digits. This could be useful when getting params from the route. The constraints can be analogous to how validations works for models.

Controller

class ErrorsController < ApplicationController
  def show
    @exception = env["action_dispatch.exception"]
    respond_to do |format|
      format.html { render action: request.path[1..-1] }
      format.json { render json: {status: request.path[1..-1], error: @exception.message} }
    end
  end
end

The @exception instance variable is set to the type of exception raised. The exception is store in the environment’s action_dispatch.exception. The action responds to different formats like html or json. Therequest.pathhas[1..-1]to turn/404to404`