In most other languages, the catch and throw statements do what the begin, rescue, and raise statements do in Ruby. I know the you can do this with these two statements:
I have been looking for a good example for a while, until I met Sinatra.
IMHO, Sinatra exposes a very interesting example usage for catch
.
In Sinatra you can immediately terminate a request at any time using halt
.
halt
You can also specify the status when halting...
halt 410
Or the body...
halt 'this will be the body'
Or both...
halt 401, 'go away!'
The halt method is implemented using throw.
def halt(*response)
response = response.first if response.length == 1
throw :halt, response
end
and caught by the invoke
method.
There are several uses of :halt
in Sinatra. You can read the source code for more examples.