1

I want to write on failure to either STDOUT or STDERR a clean, simple error message for the user, without the (verbose) backtrace, and then exit with a failed status. I am currently using raise to raise exceptions in various parts of the code that I call. I am using begin ... rescue block and abort that wraps the entire caller code as in this simplified example:

#!/usr/bin/env ruby

def bar
  is_input_valid = false # in the actual code, this is more complex and can be true/false
  if not is_input_valid
    raise "Input is not valid"
  end
  # ... more code ...
  is_ok_foo = false # in the actual code, this is more complex and can be true/false
  if not is_ok_foo
    raise "Foo is not ok"
  end
end

begin
  bar
rescue StandardError => e
  abort e.message
end

The real-life example has a much more verbose backtrace, and multiple raise statements to handle different failure modes with customized messages.

Is this the preferred (e.g., the most maintainable) method to handle exceptions and print just the error message and exit with a failed status?

The other alternative would be, for example, using abort instead of raise in the code, and without the begin ... rescue block.

See also:

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • Moving this question to Code Review Stack Exchange: https://codereview.stackexchange.com/questions/285164/write-a-simple-clean-error-message-without-a-backtrace-and-exit-on-failure – Timur Shtatland May 25 '23 at 14:38

0 Answers0