我正在编写一个简单的Sinatra应用程序,并且如果用户发布了具有特定数据的请求,我想返回错误“453”(自定义错误代码),其中包含消息CLIENT_ERROR或类似内容。
问题是:查看Sinatra文档并进行一些测试我找不到设置响应错误消息的方法,只有响应状态。
所以,如果设置了Sinatra响应
get '/' do
response.status = 453
end
我得到错误代码:
curl -v localhost:4567
* About to connect() to localhost port 4567 (#0)
* Trying 127.0.0.1... connected
> GET / HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:4567
> Accept: */*
>
< HTTP/1.1 453
< X-Frame-Options: sameorigin
< X-XSS-Protection: 1; mode=block
< Content-Type: text/html;charset=utf-8
< Content-Length: 0
< Connection: keep-alive
< Server: thin 1.3.1 codename Triple Espresso
<
* Connection #0 to host localhost left intact
* Closing connection #0
但我想拥有的是:
< HTTP/1.1 453 CLIENT_ERROR
和我一样
< HTTP/1.1 200 OK
当一切按照计划进行时。
无论如何使用Sinatra / Rack进行此操作?
答案 0 :(得分:4)
状态消息由您使用的服务器生成,例如简化消息在Thin::HTTP_STATUS_CODES
中,响应行在Thin::Response
中生成,在WEBrick中,它们在WEBrick::HHTPStatus::StatusMessage
中,响应在WEBrick::HTTPResponse
中生成。
如果您知道正在使用的服务器,则可以将错误添加到相应的哈希值。
使用Thin:
require 'thin'
Thin::HTTP_STATUS_CODES[453] = "Client Error"
和输出:
$ curl -v localhost:4567
* About to connect() to localhost port 4567 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 4567 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost:4567
> Accept: */*
>
< HTTP/1.1 453 Client Error
< X-Frame-Options: sameorigin
< X-XSS-Protection: 1; mode=block
< Content-Type: text/html;charset=utf-8
< Content-Length: 0
< Connection: keep-alive
< Server: thin 1.4.1 codename Chromeo
<
* Connection #0 to host localhost left intact
* Closing connection #0
和WEBrick:
require 'webrick'
WEBrick::HTTPStatus::StatusMessage[453] = "Client Error"
给出输出:
$ curl -v localhost:4567
* About to connect() to localhost port 4567 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 4567 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost:4567
> Accept: */*
>
localhost - - [13/Aug/2012:01:41:48 BST] "GET / HTTP/1.1" 453 0
- -> /
< HTTP/1.1 453 Client Error
< X-Frame-Options: sameorigin
< X-Xss-Protection: 1; mode=block
< Content-Type: text/html;charset=utf-8
< Content-Length: 0
< Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)
< Date: Mon, 13 Aug 2012 00:41:48 GMT
< Connection: Keep-Alive
<
* Connection #0 to host localhost left intact
* Closing connection #0
答案 1 :(得分:4)
我建议不要使用自定义HTTP状态代码。如果您认为自己有一些普遍用途,请考虑编写Internet草案并完成IETF规范流程。