Custom Error Handling with Rails 4.0

后端 未结 5 747
我寻月下人不归
我寻月下人不归 2020-12-24 14:49

I\'m building a Ruby on Rails api using Ruby 2.0 and Rails 4.0. My app is almost solely a JSON API, so if an error occurs (500, 404), I want to capture that error and return

5条回答
  •  长情又很酷
    2020-12-24 15:31

    I used the 404.html from public folder and this is in dev environment.
    I actually got the answer from:

    • https://stackoverflow.com/posts/20508445/revisions and
    • https://coderwall.com/p/w3ghqq

    However, I did a little experiment on what pieces of code actually made it work. Here's are the pieces of code that I only added.

    config/routes.rb

    Rails.application.routes.draw do
        // other routes
        match "*path", to: "application#catch_404", via: :all
    end
    

    app/controllers/application_controller.rb

    class ApplicationController < ActionController::Base
        def catch_404
            render :file => 'public/404.html', :status => :not_found
        end
    end
    

    Will appreciate any comments and clarifications as to why some of the original are are needed. For instance, using this line of code

    raise ActionController::RoutingError.new(params[:path])
    

    and this

    rescue_from ActionController::RoutingError, :with => :error_render_method
    

    Because rescue_from and raise ActionController::RoutingError seem to be the popular answer from the older Rails versions.

提交回复
热议问题