我遇到了以下错误:
ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")
我想为不存在的链接显示错误404页面。
我该如何实现这一点?
我遇到了以下错误:
ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")
我想为不存在的链接显示错误404页面。
我该如何实现这一点?
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
。如果我使用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
@requested_path = request.path
以及对应的调用 format.json { render json: {routing_error: @requested_path} }
吗? - Afolabi Olaoluwa@requested_path
。至于JSON,如果我确定不想返回完整页面,例如通过ajax,我可以请求返回JSON,并获取错误消息。 - Misuconfig/routes.rb
文件中添加这个的技巧是关键。 - skplunkerinapp/assets/images
目录下对我有用。错误404
页面未找到
...但您正在丢失所有活动存储图像!!!
errors_controller.rb
:) 如果是这种情况的话 - 请确保收回你的反对投票,除非你有更多原因让它保留。 - Andrey Deinekorescue_from ActionController::RoutingError, with: -> { render_404 }
呢? - depquidmatch '*path' => 'errors#error_404', via::all
。 - skplunkeringet '*path', to: 'errors#error_404', via: :all
)时,如何出现ActionController::RoutingError
错误? - B Seven