0
我正在为我的REST API使用RABL。但是,目前,即使出现错误,我得到的HTTP响应代码也是200.有没有办法将其更改为4xx级代码?这对我的客户来说很棒。使用Rails和RABL更改HTTP响应代码
我没有使用render template: "api/v1/error.rabl”
,因为如果我确实使用它,会有一个后置过滤器设置CORS访问控制标头,该标头不会被执行。
我试过搜索,但没有找到方法。
我正在为我的REST API使用RABL。但是,目前,即使出现错误,我得到的HTTP响应代码也是200.有没有办法将其更改为4xx级代码?这对我的客户来说很棒。使用Rails和RABL更改HTTP响应代码
我没有使用render template: "api/v1/error.rabl”
,因为如果我确实使用它,会有一个后置过滤器设置CORS访问控制标头,该标头不会被执行。
我试过搜索,但没有找到方法。
好像this answer提供了一个很好的解决方案。例如,
class FoosController < ActionController::Base
respond_to :json
class ApiResponder < ActionController::Responder
def to_format
case
when has_errors?
controller.response.status = :unprocessable_entity
when get? && !resource
controller.response.status = :not_found
when post?
controller.response.status = :created
end
default_render
rescue ActionView::MissingTemplate => e
api_behavior(e)
end
end
self.responder = ApiResponder
def show
@foo = Foo.find(params[:id])
@foo.errors.add(:base, "foo bar") # e.g. of errors on the object
respond_with @foo
end
end
虽然the wiki有一个警告,“设置controller.response.status
就像是一个默认值”,respond_with
或render
应该没有明确设定status
,它似乎想render "my_template"
呼叫触发200
你提到。如果你想重新使用一个单一的错误模板,something like the author's suggested template,这个工程:
...
self.responder = ApiResponder
def show
@foo = Foo.find(params[:id])
@foo.errors.add(:base, "foo bar") # e.g. of errors on the object
respond_with @foo do |format|
if @foo.errors.empty?
flash[:notice] = 'Foo was successfully created.'
else
format.json { render "error" }
end
end
end
# error.rabl
object false
node :errors do
{
:message => "Sorry, fubar'ed",
:code => 12345
}
end
这适用于作为读取写入以及行动。 original bug discussion也有一些有趣的例子。
那么你使用什么渲染调用呢? – phoet
我让控制器方法自然返回,以便Rails自动将RABL文件作为视图调用。 –
这与调用渲染自己有什么不同? – phoet