如何在Ruby脚本中获取致命错误的确切消息



我有一个Ruby脚本,该脚本从远程服务器中获取 PostgreSQL数据库dump 。脚本获取:密码,用户名,主机和数据库_NAME的动态输入。因此,用户有可能为这些字段提供错误的输入。如果输入任何错误,我会致命错误喜欢

pg_dump:[Archiver(db(]连接到数据库" SC_DEVEVELMENT1" 失败:致命:数据库" sc_development1"不存在

如果数据库错误,则在我们这样做时,

system("PGPASSWORD="#{source_postgres_password}" pg_dump -U "#{source_postgres_username}" -h "#{source_host}" "#{source_database_name}" > "#{store_backup_file_path}/#{timestamp}/#{source_database_name}".sql")

目前,我正在通过检查$?以获取过程状态来处理此问题,但我想要更多。我想获取要在日志文件中打印的确切致命错误消息。如何做?

我想打印我在终端中看到的确切的致命错误消息,从我运行脚本到日志文件的位置。

有什么办法可以给我致命错误的详细信息。我知道Ruby不可能挽救致命错误。当我阅读本文时,我可以在发生致命错误的情况下可以打印自己的消息,但这不是我想要的。我想要确切的致命错误消息。

您可以使用open3模块和capture3功能,该功能允许您捕获Stdout,stderr和状态:

[3] pry(main)> require 'open3'
=> true
[4] pry(main)> stdout, stderr, status = Open3.capture3("ls asd")
=> ["", "ls: cannot access 'asd': No such file or directoryn", #<Process::Status: pid 19314 exit 2>]

在您的情况下做:

require 'open3'
_, stderr, status = capture3(PGPASSWORD="#{source_postgres_password}" pg_dump -U "#{source_postgres_username}" -h "#{source_host}" "#{source_database_name}" > "#{store_backup_file_path}/#{timestamp}/#{source_database_name}".sql)
puts "Postgres error: #{stderr}"  unless status.error 

另请参见:https://www.honeybadger.io/blog/capturing-stdout-stderr-from-shell-commands-via-ruby/

最新更新