[英]How to redirect with InvalidAuthenticityToken error
I've discovered that the handle_unverified_request
method can be overridden in the ApplicationController
to rewrite how Rails handles InvalidAuthenticityToken
errors. 我发现可以在
ApplicationController
中重写handle_unverified_request
方法以重写Rails如何处理InvalidAuthenticityToken
错误。 By default the handle_unverified_request
will raise the InvalidAuthenticityToken
error. 默认情况下,
handle_unverified_request
将引发InvalidAuthenticityToken
错误。 I've overridden this method like so 我已经像这样重写了这种方法
def handle_unverified_request
redirect_to '/422'
end
However, I'm using Airbrake which records errors that are raised on my Rails application. 但是,我使用的是Airbrake,它记录了在Rails应用程序中引发的错误。 According to this answer , Rails can raise the error AND redirect the user to the 404 page.
根据此答案 ,Rails会引发错误并将用户重定向到404页面。 Does the same thing exist for the 422 page?
422页是否存在相同的内容? I want to raise the InvalidAuthenticityToken and redirect the user to the 422 page.
我想提出InvalidAuthenticityToken并将用户重定向到422页。 How do I do that?
我怎么做?
ApplicationController.rb ApplicationController.rb
protect_from_forgery with: :exception
rescue_from ActionController::InvalidAuthenticityToken, with: :rescue_422
def handle_unverified_request
raise(ActionController::InvalidAuthenticityToken)
end
def rescue_422
redirect_to '/422'
end
According to the link, you posted, Rails does not redirect
the user to the 404 page, it renders
404 page instead. 根据您发布的链接,Rails不会
redirect
用户redirect
到404页面,而是renders
404页面。 When InvalidAuthenticityToken
error, Rails must render
422 page by default. 当
InvalidAuthenticityToken
错误时,默认情况下,Rails必须render
422页。 It is done on Rack Middleware level. 它是在机架中间件级别上完成的。
If default behaviour is not what you want and you need redirect
and Airbrake to log the exception, then you have to handle the exception and do the redirect AFTER! 如果默认行为不是您想要的,并且您需要
redirect
和Airbrake来记录异常,那么您必须处理异常并在之后进行重定向! Airbrake logs it. 气刹记录下来。 I think that Airbrake logs exceptions on the Rake Middleware level, so you will have to somehow customize Rack Middleware's exceptions handler to get what you want.
我认为Airbrake在Rake中间件级别记录异常,因此您必须以某种方式自定义Rack中间件的异常处理程序以获取所需的内容。 You will have to find out where Airbrake logs exceptions and make sure that your custom exceptions handler works after the logging.
您将必须找出Airbrake在哪里记录异常,并确保在记录后您的自定义异常处理程序可以工作。
Are you sure you want redirect
, not render
? 您确定要
redirect
而不是render
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.