rails自定义错误异常执行是臃肿的,干涸的建议?

时间:2013-05-29 11:18:50

标签: ruby-on-rails ruby-on-rails-3 refactoring

在application_controller.rb中,有一种方法可以使用自定义布局和部分布局来渲染404错误。

application_controller.rb:

  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception, with: :render_500
    rescue_from ActionController::RoutingError,       with: :render_404
    rescue_from ActionController::UnknownController,  with: :render_404
    rescue_from ActionController::UnknownAction,      with: :render_404
    rescue_from ActiveRecord::RecordNotFound,         with: :render_404
  end

这会调用任何方法:

  def render_404(exception)
    notify exception
    @not_found_path = exception.message
    respond_to do |format|
      format.html { render template: 'errors/error_404', layout: 'layouts/error', status: 404 }
      format.all { render nothing: true, status: 404 }
    end
  end

  def render_500(exception)
    notify exception
    @error = exception
    respond_to do |format|
      format.html { render template: 'errors/error_404', layout: 'layouts/error', status: 404 }
      format.all { render nothing: true, status: 500 }
    end
  end

然后是error_controller.rb:

class ErrorsController < ApplicationController

  layout "error"

  def sub_layout
    "left"
  end

  def error_404
    @not_found_path = params[:not_found]
    render "errors/error_404"
  end

  def error_500
    render "errors/error_500"
  end

end

问题: 这感觉非常臃肿,有没有办法让它呈现现在位于/app/views/errors/error_404.html.haml的自定义错误页面?自定义布局?

我想删除我的error_controller.rb

1 个答案:

答案 0 :(得分:0)

呈现404和500 html响应的默认路径位于公用文件夹中。我将使用您的error_404.html

替换默认的404.html
render :file => 'public/404.html', :layout => layouts/error