繁体   English   中英

在 Rails 4 中,来自 ActionController::RoutingError 的救援

[英]rescue_from ActionController::RoutingError in Rails 4

我有以下错误:

ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")

我想为不存在的链接显示 error404 页面。

我怎样才能做到这一点?

application_controller.rb添加以下内容:

  # You want to get exceptions in development, but not in production.
  unless Rails.application.config.consider_all_requests_local
    rescue_from ActionController::RoutingError, with: -> { render_404  }
  end

  def render_404
    respond_to do |format|
      format.html { render template: 'errors/not_found', status: 404 }
      format.all { render nothing: true, status: 404 }
    end
  end

我通常也会拯救以下异常,但这取决于你:

rescue_from ActionController::UnknownController, with: -> { render_404  }
rescue_from ActiveRecord::RecordNotFound,        with: -> { render_404  }

创建错误控制器:

class ErrorsController < ApplicationController
  def error_404
    render 'errors/not_found'
  end
end

然后在routes.rb

  unless Rails.application.config.consider_all_requests_local
    # having created corresponding controller and action
    get '*path', to: 'errors#error_404', via: :all
  end

最后一件事是在/views/errors/下创建not_found.html.haml (或您使用的任何模板引擎):

  %span 404
  %br
  Page Not Found

@Andrey Deineko,您的解决方案似乎仅适用于在RoutingError内手动引发的RoutingError s。 如果我使用 url my_app/not_existing_path尝试它,我仍然收到标准错误消息。

我想这是因为应用程序甚至没有到达控制器,因为 Rails 之前引发了错误。

为我解决问题的技巧是在路线的末尾添加以下行:

Rails.application.routes.draw do
  # existing paths
  match '*path' => 'errors#error_404', via: :all
end

捕获所有未预定义的请求。

然后在 ErrorsController 中,您可以使用respond_to来处理 html、json... 请求:

class ErrorsController < ApplicationController
  def error_404
    @requested_path = request.path
    repond_to do |format|
      format.html
      format.json { render json: {routing_error: @requested_path} }
    end
  end
end

app/assets/images复制网站图标图像对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM