randomuser
randomuser

Reputation: 1888

Invoking halt in sinatra does not set sinatra.error

My use case is that I would like to do error handling in sinatra. For this I am setting up the error handler as follows

error 0..600 do
  @@logger.error("error reason #{env['sinatra.error']}")
end

The sinatra.error variable gets set fine if the error was caused by explicitly raising an exception

get '/' do
  raise "Fail the request"
end 

But if halt is used to terminate the request then sinatra.error does not get set. Looking into sinatra code this appears to be as expected because throwing :halt causes the control flow to go all the way up to invoke and thus bypassing the setting of sinatra.error variable.

My question is how to use the error handler along with the halt so that I can get the cause of the error in the error handler.

Upvotes: 2

Views: 703

Answers (1)

Adiel Mittmann
Adiel Mittmann

Reputation: 1764

I think the behavior you're seeing stems from the intended purpose of halt. When you call it, you aren't necessarily signaling in error; you just want execution to stop immediately, which can be particularly useful in a filter. If you check Sinatra's README, it says that you use halt to "immediately stop a request within a filter or route use". Granted, you will usually do it because of an error.

It is also interesting to notice that the error handler you defined gets called not only when errors occur, but also when regular requests are served, including ones with status 200. And in those cases, env[sinatra.error] won't be set either.

What you can do in your error handler is to check for an exception and, if it's not available, check the response code. For example (note that this is a classical application):

error 0..600 do
  boom = @env['sinatra.error']
  status = response.status
  case
  when boom != nil
    puts 'exception: ' + boom
  when status != 200
    puts 'error: ' + status
  end
end

One consequence is that, in this handler, normal requests are indistinguishable from those interrupted by halt, because both generate a 200 status code. However, if you are using halt to report errors, then you should be using an error code like 500 anyway.

Upvotes: 2

Related Questions