Tips to Debug Ruby CGI script

In Ruby CGI script, error messages are printed only in log file. If you got any errors, you must look up log file to know what and where error raised. This is not difficult, but a bother thing.

The following script named ‘cgi_exception.rb’ is a tiny script to display exception in browser like PHP. If you require ‘cgi_exception’, it will help you to know what and where exception raised.

##
## cgi_exception.rb
##

def _esc_html(s)
  s.to_s.gsub(/&/,'&amp;').gsub(/</,'&lt;').gsub(/>/,'&gt;').gsub(/"/,'&quot;')
end

def _print_stack_trace(ex, out=$stderr, header="Content-Type: text/html\r\n")
  out ||= $stderr
  out << header << "\r\n" if header
  arr = ex.backtrace
  out << "<pre style=\"color:#CC0000\">"
  out << "<b>#{_esc_html arr[0]}: #{_esc_html ex.message} (#{ex.class.name})</b>\n"
  arr[1..-1].each {|s| out << "        from #{_esc_html s}\n" }
  out << "</pre>"
end

at_exit do
  _print_stack_trace($!, $stdout) if $!
end

I have packaged the above script to cgi-exception-0.1.0.gem and just released it. You can install it by ‘gem install cgi-exception’.

Leave a reply