【问题标题】:Rails and ajax global error handling issueRails 和 ajax 全局错误处理问题
【发布时间】:2013-01-25 05:36:44
【问题描述】:

我有以下全局 ajax 错误处理程序:

App.Utils.AjaxGlobalErrorHandler = {

  isUnauthenticatedStatus: function (request) {
    var status = request.status
    return status == 403;
  },

  displayError: function() {
    $('#ajax-error-modal-window').modal('show');
    $('#ajax-error-message').append("An error occurred. Please, try again.");
  },

  errorMsgCleanup: function() {
    $('#ajax-error-modal-window').on('hidden', function() {
      $('#ajax-error-message').empty();
    });
  },

  handleUnauthorized: function() {
    if ($('#signin').length == 0) {
      window.location = '/signin';
    }
    else {
      $('#signin').trigger('click');
    }
  },

  bindEvents: function() {
    $(document).ajaxError(function(e, xhr, settings, exception) {
      if (App.Utils.AjaxGlobalErrorHandler.isUnauthenticatedStatus(xhr)) {
        App.Utils.AjaxGlobalErrorHandler.handleUnauthorized();
      }
      else {
        App.Utils.AjaxGlobalErrorHandler.displayError();
        App.Utils.AjaxGlobalErrorHandler.errorMsgCleanup();
      }
    });
  }

};

然后是标准的 Rails 全局异常处理:

class ApplicationController < ActionController::Base
  rescue_from Exception, :with => :handle_exceptions

  protected

  def handle_exceptions(e)
    case e
    when AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, ActionController::RoutingError
      not_found
    else
      internal_error(e)
    end
  end

  def not_found
    render :file => "#{Rails.root}/public/404.html", :layout => false, :status => 404
  end

  def internal_error(exception)
    if Rails.env == 'production'
      ExceptionNotifier::Notifier.exception_notification(request.env, exception).deliver
      render :file => "#{Rails.root}/public/500.html", :layout => false, :status => 500
    else
      throw exception
    end
  end

end

如您所见,我的 ajax 错误处理显示了一个对话框。我遇到的问题是,当我通过在返回 html 响应的控制器操作中引发 ActiveRecord::RecordNotFound 异常来测试错误处理时,在 Rails 呈现 404 页面之前触发 ajaxError 事件,显示对话框,然后在呈现 404 页面后消失。我没想到在这种情况下会触发 ajaxError 事件。有人可以解释为什么吗?当异常应该由服务器端处理时,如何避免触发 ajaxError? 顺便说一句,我正在使用 pjax

【问题讨论】:

    标签: jquery ruby-on-rails ajax error-handling pjax


    【解决方案1】:

    这是因为 jQuery 将 404 作为错误处理:https://github.com/jquery/jquery/blob/master/src/ajax.js#L613

    在您提供的示例中,服务器在应用程序控制器中捕获 ActiveRecord::RecordNotFound 异常并返回#not_found 的结果。作为响应,jQuery 检测到 404 并引发 ajaxError 事件。

    希望这会有所帮助。

    【讨论】:

    • 太棒了。这肯定解释了这个问题。对于我的问题的第二部分,如何避免这个问题?
    • 您能否解释一下为什么这对您来说是个问题,您希望服务器/客户端准确地做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多