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

时间:2022-10-24 13:09:44

I'm pretty new in rails, and using rails 4.

我在rails中很新,并且使用rails 4。

In my application I want to return all 404 and 500 errors formatted on JSON like that

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

{
    "status": 404,
    "message": "not found"
}

There is an easy way to do this ? cause I just find solutions to do this with rails 3.x.

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

Thanks

谢谢

I trying to do this solution Need to return JSON-formatted 404 error in Rails but I get error during failsafe response: uninitialized constant ErrorsController

我试图做这个解决方案需要在Rails中返回JSON格式的404错误但我在故障安全响应期间收到错误:uninitialized constant ErrorsController

1 个解决方案

#1


11  

May be you're looking for this:

可能你在找这个:

render :json => @error_object.to_json, :status => :unprocessable_entity

And probably you may catch all standard errors like this:

也许您可能会遇到所有标准错误:

class ApplicationController < ActionController::Base
  rescue_from StandardError do |exception|
    # render what you want here
  end
end

#1


11  

May be you're looking for this:

可能你在找这个:

render :json => @error_object.to_json, :status => :unprocessable_entity

And probably you may catch all standard errors like this:

也许您可能会遇到所有标准错误:

class ApplicationController < ActionController::Base
  rescue_from StandardError do |exception|
    # render what you want here
  end
end