在 Ruby on Rails 中 AJAX 调用失败时重定向到 500 页面
我正在使用一个用 Ruby on Rails 构建的应用程序,目前错误处理能力非常差。 如果通过 ajax 执行控制器方法,并且该方法导致 500(或 404 或任何其他响应),则将呈现 500.html 页面并将其作为 AJAX 请求的结果返回。 显然,JavaScript 不知道如何处理该 HTML,并且网页看起来只是在等待响应。
Rails 中是否有一种简单的方法可以在 AJAX 调用期间发生错误时呈现 error.rjs 模板?
I'm working with an application built in Ruby on Rails with very poor error handling right now. If a controller method is executed via ajax, and that method results in a 500 (or 404 or any other response) the 500.html page is rendered and returned as the result to the AJAX request. Obviously the javascript doesn't know what to do with that HTML and the web page looks like it's just waiting for a response.
Is there an easy way in rails to render an error.rjs template anytime an error occurs during an AJAX call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在控制器的rescue_action 或rescue_action_in_public 方法中使用respond_to。 考虑以下控制器:
You can use respond_to inside a controller's rescue_action or rescue_action_in_public method. Consider the following controller:
我通过授权解决了类似的问题。 我使用此操作创建了一个简单的授权控制器:
这是模板:
当控制器中的授权失败时,我会在设置 flash[ 后重定向到 :controller=>"authorization", :action=>"unauthorizedxhr" :注意]值。 这允许我自定义发送给用户的消息,并通过上面的 render :update 代码处理消息的显示。
您可以通过创建错误控制器来适应您的问题,捕获其他控制器中出现的任何错误,然后在调用失败时简单地重定向到 :controller=>"errors", :action=>"displayxhr" 。 这样,您就可以标准化错误通信机制,同时允许自己通过每个操作自定义错误消息。
您仍然可以使用上面 cpm 的想法,但错误的显示将由单独且不同的控制器逻辑处理。 这应该使它更容易维护。
希望有帮助。
-克里斯
I solved a similar problem with authorization. I created a simple authorization controller with this action:
Here's the template:
When the authorization failed in the controller, I'd redirect to the :controller=>"authorization", :action=>"unauthorizedxhr" after setting the flash[:notice] value. This allowed me to customize the message I sent to the user, and it handled the display of the message through the render :update code above.
You could adapt this to your problem by creating an errors controller, catching any raised errors in your other controllers, then simply redirecting to :controller=>"errors", :action=>"displayxhr" when the call fails. That way, you'll have standardized your error communication mechanism but allowed yourself the ability to customize error messages by each action.
You can still use cpm's idea above, but the error's display will be handled by separate and distinct controller logic. that should make it a little easier to maintain.
Hope that helps.
-Chris
这是我的最终解决方案:
无论请求是通过 AJAX 还是普通 GET/POST,这基本上都会转发到正确的静态 HTML 页面。
这不用于正常的错误处理,例如验证等。它仅在发生非常糟糕的事情时使用 - 例如未处理的异常。
This was my final solution:
This basically forwards to the correct static HTML page no matter if the request was via AJAX or normal GET/POST.
This is NOT used for normal error handling like validation etc. It's only used when something really bad happens - like an unhandled exception.
你可以像下面这样做:
在 allpication.js
它对我有用......
You can do like below :
in allpication.js
Its working for me.....