ruby-on-rails – rescue_from ActionController :: RoutingError in Rails 4

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – rescue_from ActionController :: RoutingError in Rails 4前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下错误
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
原文链接:https://www.f2er.com/ruby/266681.html

猜你在找的Ruby相关文章