Rails 如何统一捕获路由错误

mingmingpao · July 06, 2015 · Last by lazing replied at July 06, 2015 · 2098 hits

Rails 中如何统一捕获路由不存在的错误,而不是抛出默认界面。我在开发环境下使用:

rescue_from ActionController::RoutingError do |ex| 
  render json: 'hello' #TODO No use for rescue from routing error
end

没有看到效果。

routes.rb

match '*path', via: :all, to: 'controller#action'

比较好的方式是配置 exception_app

# application.rb
    config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
    config.action_dispatch.rescue_responses["ActionController::RoutingError"] = :not_found
    config.action_dispatch.rescue_responses["ActionController::BadRequest"] = :bad_request

checkout the thread and the gem

http://stackoverflow.com/questions/19103759/rails-4-custom-error-pages-for-404-500-and-where-is-the-default-500-error-mess

https://github.com/richpeck/exception_handler

You need to Sign in before reply, if you don't have an account, please Sign up first.