在 Rails 4 中,来自 ActionController::RoutingError 的救援 [英] rescue_from ActionController::RoutingError in Rails 4

查看:35
本文介绍了在 Rails 4 中,来自 ActionController::RoutingError 的救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下错误:

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

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

I want to show error404 page for links that are not existing.

我怎样才能做到这一点?

How can I achieve that?

推荐答案

application_controller.rb 中添加以下内容:

In application_controller.rb add the following:

  # 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

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

I usually also rescue following exceptions, but that's up to you:

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(或您使用的任何模板引擎):

And the last thing is to create not_found.html.haml (or whatever template engine you use) under /views/errors/:

  %span 404
  %br
  Page Not Found

这篇关于在 Rails 4 中,来自 ActionController::RoutingError 的救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆