Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails3中的异常处理_Ruby On Rails_Exception - Fatal编程技术网

Ruby on rails Rails3中的异常处理

Ruby on rails Rails3中的异常处理,ruby-on-rails,exception,Ruby On Rails,Exception,我想在Rails 3中处理我自己的异常。在Rails3中,处理自定义异常和路由错误的最佳过程是什么 您可以按如下方式处理自定义异常: 在应用程序控制器中,添加以下内容: rescue_from Exception, :with => :handle_exception def not_found render :template => "shared/not_found", :status => 404 end private def handle_

我想在Rails 3中处理我自己的异常。在Rails3中,处理自定义异常和路由错误的最佳过程是什么

您可以按如下方式处理自定义异常: 在应用程序控制器中,添加以下内容:

rescue_from Exception, :with => :handle_exception

  def not_found
    render :template => "shared/not_found", :status => 404
  end

  private
  def handle_exception(exception)
    case exception
    when CanCan::AccessDenied
      authenticate_user!
    when ActiveRecord::RecordNotFound
      not_found
    else
      internal_server_error(exception)
    end
  end

  def internal_server_error(exception)
    render :template => "shared/internal_server_error", :status => 500
  end
现在,在方法中,您可以引发错误或异常,如下所示:

def method_name
  # raise exception_name, "message on exception"
  raise ArgumentError, "missing some param"
end
您还可以通过如下方式添加路由来捕获路由错误:

match "*any", :to => "application#not_found"
注意:您应该在route.rb的末尾添加上述路线