Writing in Rack with a complete error catch

Man, forgetting to add my little error catching trick inside of one app I was writing made me realize how much I take such a simple trick for granted.

app = proc do |env|
  # Application code
  rescue Exception => e
  r = Rack::Response.new
  r.status = 500
  r.header["Content-Type"] = "text/plain"
  r.body = e.to_s << "\n" << "-" * e.to_s.length << "\n" << e.backtrace.join("\n")

run app

I basically write all my rack code in a way similar to that. Normally I'll probably throw in another error catching level that catches special formated ErrorPage classes for things like NoPage to generate a 404. But this here is the big absolute fallback, if at any point inside of my code I make a mistake in syntax or anything this completely catches it, and renders the full error message and a full backtrace letting me actually see the error right away instead of looking through a horrid apache log.

  • programming
  • code
  • ruby