I have a Ruby script that take PostgreSQL database dump from the remote server. Script takes dynamic input for: password, username, host and database_name. So there is chance that user can provide wrong input for these fields. In case of any wrong input I get fatal error like
pg_dump: [archiver (db)] connection to database "sc_development1" failed: FATAL: database "sc_development1" does not exist
in case of wrong database while we do as,
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")
Currently I am handling this by checking $?
to get process status but I want more. I want to get the exact Fatal error message to print in a log file. How to do this?
I want to print the exact fatal error message that I am seeing in the terminal from where I run the script to the log file.
Is there any way that can give me details of Fatal error. I know it's not possible in Ruby to rescue fatal error. As I read this I can print my own message as it handle in case of fatal error but this is not what I want. I want exact fatal error message.
You can use open3
module and capture3
function that allows you to capture stdout, stderr and status:
[3] pry(main)> require 'open3'
=> true
[4] pry(main)> stdout, stderr, status = Open3.capture3("ls asd")
=> ["", "ls: cannot access 'asd': No such file or directory\n", #<Process::Status: pid 19314 exit 2>]
Do in your case:
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
See also: https://www.honeybadger.io/blog/capturing-stdout-stderr-from-shell-commands-via-ruby/