【问题标题】:Generating the Error Page for a 422 Error为 422 错误生成错误页面
【发布时间】:2017-05-25 11:50:19
【问题描述】:

我目前正在为 500 和 404 错误生成动态错误页面。我想将此扩展到 422 错误。这是我们目前所拥有的。

config/application.rb

config.exceptions_app = self.routes

控制器/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

routes.rb

get '/404' => 'errors#not_found'
get '/500' => 'errors#internal_server_error'
get '/422' => 'errors#unacceptable'

public/422.html 页面已被删除。错误视图页面已创建,但为简洁起见省略。当出现 404 或 500 错误时,将显示错误页面。但是,当我收到 422 错误时,我会看到以下错误页面。

我已经看到许多教程实现了相同的方法,并且它很有效。但是,我收到的是生成的 Rails 错误,而不是我创建的错误页面。出了什么问题,我该如何解决?

我看过的教程:

【问题讨论】:

  • 你试过rescue_from吗?
  • 我找到的教程都没有使用rescue_from。我将发布指向我在问题中查看的教程的链接。
  • 这就是我链接到它的原因。 Rails 文档比大多数教程更深入地介绍了这一点。
  • 是的,我用过rescue_from,它运行良好。我希望我不必首先使用rescue_from。没有其他教程提到这种方法,如果我可以摆脱 rescue_from 和它调用的方法,那么我会简化我的代码。
  • 你为什么希望这样?这是工作的工具。这是表达你想做的最简单的方式。默认是失败。

标签: ruby-on-rails ruby ruby-on-rails-4 routes http-status-code-422


【解决方案1】:

我是另一位与@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' =&gt; 'errors#unprocessable_entity'

此时,一般 422 错误按应有的方式执行。我们设置了一个控制器动作,当你点击它时,它会引发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 错误的影响。

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 2019-09-21
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2011-03-26
    • 2020-12-07
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多