首页 > 解决方案 > 服务器回复默认调试响应而不是引发的异常响应

问题描述

在带有 API 的引擎中,查询 API 时会引发异常,但服务器响应未使用指定的响应,而是呈现默认调试响应(在生产中)。

我可以确认异常被控制器捕获:

Started GET "/api_v2/admin/submissions?system_id=123&spt_id=123" for 

127.0.0.1 at 2019-03-15 10:04:37 -0400
Processing by ApiV2::Admin::SubmissionsController#show as JSON
  Parameters: {"system_id"=>"123", "spt_id"=>"123"}

[3, 12] in /....../emp_api_v2/app/controllers/emp_api_v2/application_controller.rb
    3: 
    4:     before_action :doorkeeper_authorize!
    5: 
    6:     rescue_from ::ActiveRecord::RecordNotFound do |e|
    7:       byebug
=>  8:       response(:standard_error, 500, "Hello World")
    9:     end
   10: 
   11:     def doorkeeper_unauthorized_render_options(error: nil)
   12:       { json: { message: "Not authorized" }, status: 403 }
(byebug) cont
Completed 500 Internal Server Error in 5220ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound - Couldn't find Emp::System with 'id'=123:

服务器应该以 500 服务器错误而不是调试错误堆栈跟踪来响应。

为什么有两个响应,即使控制器捕获到异常并运行响应方法。

注意:这发生在 dev 和 prod 中!服务器首先响应 500(我的 catch 响应),然后是堆栈跟踪和 404(因为这是错误和正确异常的来源)。它打破了我的测试,因为过去的响应是 500。我无法通过以下方式将我的服务器恢复到旧的行为:重新安装 ruby​​,重新安装 rails + 所有 gems + 回滚整个 repo 中的所有更改。这种行为似乎是由 ENV 变量或其他东西在外部设置的。

我会很感激任何见解。

编辑:(api)应用程序控制器如下所示:

module ApiV2
  class ApplicationController < ActionController::API

    before_action :doorkeeper_authorize!

    rescue_from ::ActiveRecord::RecordNotFound do |e|
      response(:standard_error, 500, "Hello World")
    end

    def doorkeeper_unauthorized_render_options(error: nil)
      { json: { message: "Not authorized" }, status: 403 }
    end
  end
end

编辑 2:我能够通过将呼叫包装在救援块中来获得正确的响应。该代码将导致许多开始/救援块,尽管每个块都有特定的错误消息。

    begin
      system =   Emp::System.find(sys_id)
    rescue
      render json: { status: 500, content: "Specific Error msg" } and return
    end

最初我有一个方法如下:

def handle_exception(message, &block)
  begin
    block.call
  rescue Exception => e
    render json: { message: message }, status: 500 and return
  end
end

这将导致双重渲染错误,因为它不是从顶级方法返回而是从块返回。

标签: ruby-on-railsruby-on-rails-5

解决方案


推荐阅读