加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – rescue_from ActionController :: RoutingErro

发布时间:2020-12-16 21:56:57 所属栏目:百科 来源:网络整理
导读:我有以下错误: ActionController::RoutingError (No route matches [GET] "/images/favicon.ico") 我想显示不存在的链接的错误404页面. 我该如何实现呢? 解决方法 在application_conroller.rb中添加以下内容: # You want to get exceptions in developmen
我有以下错误:
ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")

我想显示不存在的链接的错误404页面.

我该如何实现呢?

解决方法

在application_conroller.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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读