当出现错误时,Rails 在请求 JSON 时呈现 HTML [英] Rails renders HTML when JSON is requested when there is an error

查看:44
本文介绍了当出现错误时,Rails 在请求 JSON 时呈现 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Rails 用作仅 JSON 的 API 服务器,但是每当控制器中出现异常时,例如尝试删除不存在的 ID 为 1 的记录,Rails 不会响应它以 HTML 响应 JSON,可以是开发中的跟踪,也可以是生产中的通用出现问题"页面.

I'm using Rails as a JSON-only API server but whenever there is an exception in the a controller, say attempting to delete a record with an ID of 1 when it doesn't exist, Rails doesn't respond with JSON it responds with HTML, either a trace if in development or a generic 'something went wrong' page in production.

现在我正在将所有内容包装在救援中并手动吐出 JSON 响应...

Right now I'm wrapping everything in a rescue and spitting out a JSON response manually...

class AmazonAccountsController < ApplicationController

  respond_to :json, :xml

  def destroy
    # Handle bad API calls.
    begin
      @account = AmazonAccount.find(params[:id])
      @account.destroy
      # unrelated code...
    rescue
      render :json => {:errors => {:bad => "ID doesn't exist."}}.to_json
    end
  end

end

但这似乎不是处理这个问题的理想方式.

but this doesn't seem like the ideal way to handle this.

这是在 Rails 3 中.

This is in Rails 3.

推荐答案

您正在寻找 <代码>rescue_from:

You're looking for rescue_from:

如果您想在捕获错误时做一些更复杂的事情,您可以使用 rescue_from,它可以处理整个控制器及其子类中特定类型(或多种类型)的异常.

If you want to do something a bit more elaborate when catching errors, you can use rescue_from, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.

当发生由 rescue_from 指令捕获的异常时,异常对象将传递给处理程序.处理程序可以是传递给 :with 选项的方法或 Proc 对象.您也可以直接使用块而不是显式的 Proc 对象.

When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.

所以你可以这样做:

class ApplicationController < ActionController::Base
    rescue_from your_list_of_exceptions..., :with => :some_exception_handler
private
    def some_exception_handler
        render :json => { :error => 'some error message of some sort' }, :status => :unprocessable_entity # or whatever status makes sense.
    end
end

关于 rescue_from 的 API 文档代码>也值得一看.

这篇关于当出现错误时,Rails 在请求 JSON 时呈现 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆