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