【问题标题】:Ruby: Catching Sequel::DatabaseConnectionErrorRuby:捕捉 Sequel::DatabaseConnectionError
【发布时间】:2016-02-12 04:06:41
【问题描述】:

我正在使用 Docker 运行我的 Ruby 应用程序,并使用 MySQL 作为数据库。我需要让我的 Ruby 应用程序等到 MySQL 完成加载并且可以建立连接。

我正在使用以下代码:

def connect_to_db
  begin
    puts "Trying to connect to Mysql"
    Sequel::Model.db = Sequel.connect( // Connection stuff in here )
  rescue Sequel::Error => e
    puts "Mysql connection failed #{e.message}: Retrying."
    retry
  end
end

connect_to_db()

这运行一次,然后我收到一个错误 - Sequel::DatabaseConnectionError: Mysql2::Error: Unknown MySQL server host (25) - 它没有进入 rescue 块并且不会重试。

我试过rescue Sequel::DatabaseConnectionError,但结果相同。

我需要在这里拯救什么?

【问题讨论】:

  • 这不起作用的原因是 Sequel 在需要运行查询之前不会连接,并且您没有尝试在 connect_to_db 方法中运行查询。

标签: mysql ruby-on-rails ruby docker sequel


【解决方案1】:

使用db.test_connection

def connect_to_db_with_mysql_driver
  begin
    puts "Trying to connect to Mysql"
    db = Sequel.connect(
            // Connection stuff
          )
    if db.test_connection == true
      Sequel::Model.db = db
    else
      raise "Mysql connection failed."
    end
  rescue => ex
    puts ex
    puts "Retrying..."
    retry
  end
end

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多