Sinatra: regarding filters, stops and body with 404 error

I am using Sinatra to develop this JSON API. As I developed it, error messages are also sent to JSON in a specific format. The only difference is that they will have a status code of 4xx instead of 2xx or 3xx. Now the problems that I encountered:

  • I defined a general filter in which I set the content type of the response. Like this:

    before { content_type :json } 

    problem, every time I call halt, this parameter is not taken into account. I have to configure it to stop the call in a very ugly, more verbose and error prone way:

     halt [404, {"Content-Type" => "application/json;charset=utf-8"}] 

    is there any other way to do this?

  • The problem that is phasing me the most: when I stop with the 404 code after I catch the 404 error (see below), the JSON content type and json body are strange, I don't get any body, neither browser nor curl. How so?

     error 404 do halt [404...{"bang" => "bong"....}] end 

UPDATE

Regarding the last issue, here's what happens using curl and making a call that will fall into 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 

perhaps this helps.

+4
source share
2 answers

I can't figure out exactly what the result is, but if you want to override 404, you will need to do something like below, not error 404 do

 not_found do # Set content {"bang" => "bong"} end 
0
source

What version of Sinatra did you use? Looking at the latest change logs for Sinatra, I see two entries in versions 1.4.x that they find useful:

  • The state, headers and body will be correctly set in the filter after use when stopping in front of the filter or route. (Konstantin Haase)

  • Setting the status code to 404 in the error handler no longer calls the not_found handler. (Konstantin Haase)

0
source

All Articles