ruby-on-rails - 服务器回复默认调试响应而不是引发的异常响应
问题描述
在带有 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
这将导致双重渲染错误,因为它不是从顶级方法返回而是从块返回。
解决方案
推荐阅读
- simulink - 如何模拟 Sent_Protocl_signal?
- java - 新 Java 9 日志记录与现有日志记录 API 的关系
- isabelle - 如何通过评估简化归纳谓词?
- javascript - 如何为我的排行榜创建两列?
- java - 如何从另一个类调用存储在 applicationScope 中的 ArrayList
- angular - 如何使用 mocha 设置 angular.io 测试
- python - 如何将应用程序附加到原始 IP 和 TCP 层
- python - 如何通过在循环中向后访问来访问字符串的一部分
- struct - 结构的swift变量在switch语句中不可用
- dart - 如何在构建方法之外访问 State 类中的 Stateful 小部件变量?