Handling Rails 404 and 500 errors

本文提供了一种在Rails应用中处理404和500错误的方法。通过修改控制器和路由配置,可以实现定制化的错误页面展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I spent a couple of hours trying to figure out how to handle 404 and 500 errors in Rails. This is not simple and actually really annoying. Hopefully future versions clean this up because right now it sucks pretty badly. Anyways, I found a page on the wiki and some other blogs, but the issue was that they wouldn’t handle all the cases. So, here’s the solution:

1. Edit your app/controllers/application.rb file and add these three methods:

  def rescue_404
    rescue_action_in_public CustomNotFoundError.new
  end

  def rescue_action_in_public(exception)
    case exception
      when CustomNotFoundError, ::ActionController::UnknownAction then
        #render_with_layout "shared/error404", 404, "standard"
        render :template => "shared/error404", :layout => "standard", :status => "404"
      else
        @message = exception
        render :template => "shared/error", :layout => "standard", :status => "500"
    end
  end

  def local_request?
    return false
  end

The first method will be explained in the next step. The second method is the method that Rails calls to handle most errors. This method will not capture a certain class of errors where neither the controller nor the action requested exist. The third method tells rails to stop sucking. Normally Rails handles requests made to localhost or 127.0.0.1 differently than all others. This might be for debugging purposes, but it sucks when testing error handling.

2. Edit config/routes.rb and add this line TO THE END OF THE FILE:

  map.connect '*path', :controller => 'application', :action => 'rescue_404' unless ::ActionController::Base.consider_all_requests_local

This tells Rails that if it can’t find any other route to handle the request (i.e. the *path) it should call the rescue_404 action on the application controller (the first method above).

3. Edit config/environments/development.rb and add this line:

ActionController::Base.consider_all_requests_local = false

This additionally tells Rails to stop sucking and stop handling requests to localhost and 127.0.0.1 differently.

Anyways, happy coding.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值