我当前正在为 500 和 404 错误生成动态错误页面。我想将其扩展到 422 错误。这是我们到目前为止所拥有的。
配置/application.rb
config.exceptions_app = self.routes
Controller /errors_controller.rb
class ErrorsController < ApplicationController
def not_found
render status: 404
end
def internal_server_error
render status: 500
end
def unacceptable
render status: 422
end
end
路线.rb
get '/404' => 'errors#not_found'
get '/500' => 'errors#internal_server_error'
get '/422' => 'errors#unacceptable'
public/422.html 页面已被删除。错误 View 页面已创建,但为了简洁而省略。当出现 404 或 500 错误时,会显示错误页面。但是,当我收到 422 错误时,我会看到以下错误页面。
我看过很多教程都实现了同样的方法,而且它很有效。但是,我收到生成的 Rails 错误,而不是我创建的错误页面。出了什么问题以及如何解决这个问题?
我看过的教程:
最佳答案
我是另一位与 @jason328 一起从事此工作的开发人员。事实证明这是一个由多部分组成的问题,首先是一般的 422 错误,然后是 Rails 引发 ActiveRecord::InvalidAuthenticityToken
且未呈现适当页面的特定场景。
1。一般 422 错误
Rails 错误页面
我们通过设置 config.consider_all_requests_local = false 在本地开发环境中暂时摆脱了这个问题。但随后我们没有得到自定义错误页面,而是得到了一个空白页面。
空白页
根据 this Stack Overflow question ,我们需要 match '/422', to: 'errors#unprocessable_entity', via: :all
作为路由,而不是 get '/422' => 'errors#unprocessable_entity'
.
此时,一般 422 错误已按其应有的方式执行。我们设置了一个 Controller 操作,一旦您点击它,它就会引发 ActiveRecord::InvalidAuthenticityToken
,并呈现我们的自定义 422 页面。因此,对于一般遇到 422 错误问题的人来说,上述内容应该可以满足您的要求。
2。无效AuthenticityToken
但是由于 422 错误的常见原因实际上是在野外出现 InvalidAuthenticityToken
错误,因此似乎值得描述我们所看到的其余问题。在应用生成自己的 InvalidAuthenticityToken
错误的实际场景中,我们现在收到的是纯文本 500 错误,而不是我们的自定义 422 页面。
纯文本 500 错误
我们能够将此追踪到 ActionDispatch::ShowExceptions#render_exception
中的 FAILSAFE_RESPONSE
。这是 Rails 获取抛出的异常并将其转换为 [status, body, headers]
响应数组的地方。如果在此期间抛出另一个异常,它不会陷入无限循环,而是放弃并返回 FAILSAFE_RESPONSE 。在这种情况下,在整理响应时会引发另一个 InvalidAuthenticityToken
错误。
此时,是时候采用 :rescue_from
策略了:
rescue_from ActionController::InvalidAuthenticityToken,
with: :rescue_invalid_authenticity_token
def rescue_invalid_authenticity_token
#...notify services as if this error weren't being rescued
redirect_to '/422'
end
使用重定向来确保我们免受同一请求中更多 InvalidAuthenticityToken
错误的影响。
关于ruby-on-rails - 生成 422 错误的错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41578159/