Rails和ajax全局错误处理问题

时间:2013-02-09 15:47:22

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

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

1 个答案:

答案 0 :(得分:1)

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

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

希望这有帮助。