【发布时间】:2016-08-01 12:16:27
【问题描述】:
我已经编写了一个 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 时,它会引发双重渲染异常,因为渲染已经在控制器中调用。
有没有办法覆盖/关闭初始渲染调用?
红宝石 2.1.8
导轨 4.2.6
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4