我编写了一个 API,可以从所有 StandardError 中拯救出来。如果出现任何 StandardError,我会发送异常电子邮件并渲染带有错误消息的 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 UsersController < ApplicationController
def create
User.transaction do
@user = User.new(user_params)
authorize @user
@user.save!
end
respond_to do |format|
format.json { render :show, status: :created, location: @user }
end
end
end
除非从 UserController#create 中的 render :show 引发异常,否则效果很好。然后,当我再次在 ApplicationController 中使用来自 respond_with_error 的错误消息渲染 json 时,它会引发双重渲染异常,因为渲染已在 Controller 中调用。
有没有办法覆盖/取消初始渲染调用?
ruby 2.1.8
rails 4.2.6
最佳答案
尝试在操作本身中添加救援 block 。
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
只需使用redirect_to @user 即可呈现显示页面。
关于ruby-on-rails - 有没有办法重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36546937/