Ruby on rails 有没有重新渲染的方法?

Ruby on rails 有没有重新渲染的方法?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我已经编写了一个API,在其中我从所有标准错误中解救出来。如果出现任何标准错误,我会发送一封异常电子邮件,并用错误消息呈现json class ApplicationController < ActionController::Base rescue_from StandardError, with: :respond_with_error def respond_with_error(e) ExceptionNotifier.notify_exceptio

我已经编写了一个API,在其中我从所有标准错误中解救出来。如果出现任何标准错误,我会发送一封异常电子邮件,并用错误消息呈现json

class ApplicationController < ActionController::Base
    rescue_from StandardError, with: :respond_with_error
    def respond_with_error(e)
        ExceptionNotifier.notify_exception(e)
        respond_to do |format|
            format.html { render json: {error: e.message}, status: :unprocessable_entity, content_type: 'application/json' }
            format.json { render json: {error: e.message}, status: :unprocessable_entity }
        end
    end
end
class ApplicationController

class UsersController
除非在UserController#create中从render:show引发异常,否则此操作非常有效。当我在ApplicationController中再次从respond\u with_error以错误消息呈现json时,它会引发双重呈现异常,因为控制器中已经调用了render

是否有方法覆盖/取消初始渲染调用

ruby 2.1.8


rails 4.2.6

不看任何代码很难说。但一般来说,使用return可以避免DoubleRenderException,即

render :json => response_hash and return

尝试在动作本身中添加救援块

 def create
    User.transaction do
      @user = User.new(user_params)
      authorize @user
      @user.save!
    end

    flash.now[:success] = "successfully updated"
    redirect_to @user and return 

  rescue StandardError => e
    respond_with_error(e)
  end

只需使用重定向到@user即可呈现显示页面。

感谢您的回复。我已经添加了代码。正如您所见,我需要取消导致异常的初始呈现,然后呈现一个带有错误消息的json。我希望避免在每个控制器的每个操作中添加rescue,它不会改变任何东西。关于重定向,我的rails应用程序是一个API,因此客户端应用程序需要创建的对象作为响应。
 def create
    User.transaction do
      @user = User.new(user_params)
      authorize @user
      @user.save!
    end

    flash.now[:success] = "successfully updated"
    redirect_to @user and return 

  rescue StandardError => e
    respond_with_error(e)
  end