Rails将所有404和500错误作为JSON返回

ago*_*st_ 6 ruby json ruby-on-rails http

我在rails中很新,并使用rails 4.

在我的应用程序中,我想返回在JSON上格式化的所有404和500错误

{
    "status": 404,
    "message": "not found"
}
Run Code Online (Sandbox Code Playgroud)

有一种简单的方法可以做到这一点?因为我只是找到使用rails 3.x执行此操作的解决方案.

谢谢

我试图做这个解决方案需要在Rails中返回JSON格式的404错误但我得到了error during failsafe response: uninitialized constant ErrorsController

Dan*_*sky 13

可能你在找这个:

render :json => @error_object.to_json, :status => :unprocessable_entity
Run Code Online (Sandbox Code Playgroud)

也许你可能会遇到所有这些标准错误:

class ApplicationController < ActionController::Base
  rescue_from StandardError do |exception|
    # render what you want here
  end
end
Run Code Online (Sandbox Code Playgroud)