[英]Rails 7 API only doesn't rescue from ActionController::RoutingError
In my Rails 7 API only mode, I'm trying to catch case when someone is trying to make a request into api/v1/mandate
instead of api/v1/mandates
(classic ActionController::RoutingError
case).在我的 Rails 7 API only 模式下,当有人试图向
api/v1/mandate
mandate 而不是api/v1/mandates
mandates 发出请求(经典的ActionController::RoutingError
情况)时,我试图捕捉这种情况。 In such case it will render the 404 error with some build in stuff as JSON response.在这种情况下,它将呈现 404 错误,其中包含一些内置内容作为 JSON 响应。 I want to customize that JSON error answer inside my BaseController.
我想在我的 BaseController 中自定义 JSON 错误答案。 I was trying:
我在尝试:
#base_controller.rb
module Api
module V1
class BaseController < ActionController::API
rescue_from ActionController::RoutingError, with: :render_not_found_error
private
def render_not_found_error(exception)
render json: { error: true, message: exception.message }, status: :not_found
end
end
end
end
I've also have:我也有:
#config/environments/development.rb
config.consider_all_requests_local = true
But nothing changed, still doesn't get my JSON error.但是什么都没有改变,仍然没有得到我的 JSON 错误。
You can't rescue routing errors in a controller because the exceptions occur in the routing layer, not the controller.您无法挽救控制器中的路由错误,因为异常发生在路由层,而不是控制器。
For missing routes, you need a "catch-all" route that can capture them and then forward that to a controller which performs your "exception" handling.对于丢失的路由,您需要一个可以捕获它们的“全能”路由,然后将其转发给执行“异常”处理的控制器。
In practice this often shakes out as a NotFoundController
with different actions depending on the type of route being handled.在实践中,这通常会作为
NotFoundController
摇晃出来,根据所处理的路由类型进行不同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.