Custom Error Handling with Rails 4.0

后端 未结 5 724
我寻月下人不归
我寻月下人不归 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条回答
  •  梦毁少年i
    2020-12-24 15:25

    The request isn't even hitting your app.

    You need to define a catchall route so Rails will send the request to your app rather than display an error (in development) or render the public/404.html page (in production)

    Modify your routes.rb file to include the following

    match "*path", to: "errors#catch_404", via: :all
    

    And in your controller

    class ErrorsController < ApplicationController
    
      def catch_404
        raise ActionController::RoutingError.new(params[:path])
      end
    end
    

    And your rescue_from should catch the error then.

提交回复
热议问题