Ann*_*nna 22 ruby exception-handling ruby-on-rails rescue ruby-on-rails-4
我有以下错误:
ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")
Run Code Online (Sandbox Code Playgroud)
我想为error404页面显示不存在的链接.
我怎样才能做到这一点?
And*_*eko 56
在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
Run Code Online (Sandbox Code Playgroud)
我通常也会在例外情况下进行救援,但这取决于你:
rescue_from ActionController::UnknownController, with: -> { render_404 }
rescue_from ActiveRecord::RecordNotFound, with: -> { render_404 }
Run Code Online (Sandbox Code Playgroud)
创建错误控制器:
class ErrorsController < ApplicationController
def error_404
render 'errors/not_found'
end
end
Run Code Online (Sandbox Code Playgroud)
然后进去 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
Run Code Online (Sandbox Code Playgroud)
最后一件事是在下面创建not_found.html.haml(或者你使用的任何模板引擎)/views/errors/:
%span 404
%br
Page Not Found
Run Code Online (Sandbox Code Playgroud)
Mis*_*isu 10
@Andrey Deineko,您的解决方案似乎仅适用于在控制器RoutingError内手动提出的s。如果我尝试使用 url my_app/not_existing_path,我仍然会收到标准错误消息。
我想这是因为应用程序甚至没有到达控制器,因为 Rails 之前引发了错误。
为我解决问题的技巧是在路线的末尾添加以下行:
Rails.application.routes.draw do
# existing paths
match '*path' => 'errors#error_404', via: :all
end
Run Code Online (Sandbox Code Playgroud)
捕获所有未预定义的请求。
然后在 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19838 次 |
| 最近记录: |