Reputation: 5688
I'm using Sinatra to develop this JSON API. The way I designed it, the error messages are also delivered in JSON in a specific format. The only difference is that they response will have a 4xx status code instead of a 2xx or 3xx. Now, the problems I encountered:
I defined a general filter where I set the response content type. Like this:
before { content_type :json }
problem is, everytime I call halt, this setting is not taken into account. I have to set it myself on the halt call in a very ugly, more verbose and error-prone way:
halt [404, {"Content-Type" => "application/json;charset=utf-8"}]
is there another way to do this?
The problem that phases me the most is: when I halt with code 404 after I catch the 404 error (see below), JSON content type and json body, strangely, I don't get any body, neither browser nor curl gets it. How come?
error 404 do
halt [404...{"bang" => "bong"....}]
end
UPDATE
Concerning the last issue, here is what it happens using curl and triggering a call which will fall in the 404 error block:
curl http://faulty_url
# curl log:
curl: (52) Empty reply from server
# sinatra log:
!! Unexpected error while processing request: Content-Length header was 221, but should be 227
127.0.0.1 - - [28/Mar/2013 11:28:47] "GET / HTTP/1.1" 404 221 0.0664
maybe this helps.
Upvotes: 4
Views: 1118
Reputation: 384
Which version of Sinatra were you using? Looking at the recent change logs for Sinatra I see two entries in the 1.4.x releases that seem like they could be relevant:
Status, headers and body will be set correctly in an after filter when using halt in a before filter or route. (Konstantin Haase)
Setting status code to 404 in error handler no longer triggers not_found handler. (Konstantin Haase)
Upvotes: 0
Reputation: 4197
I may not understand exactly what's the output, but if you are looking to override 404 you will have to do something like below instead of error 404 do
not_found do
# Set content
{"bang" => "bong"}
end
Upvotes: 0