2

次のグローバル 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::RecordNotFoundhtml 応答を返すコントローラー アクションで例外を発生させてエラー処理をテストすると、Rails が 404 ページをレンダリングする直前に ajaxError イベントがトリガーされ、ダイアログ ボックスが表示され、404 ページがレンダリングされると消えます。この場合、ajaxError イベントがトリガーされるとは思いませんでした。誰かが理由を説明できますか?また、サーバー側で例外を処理する必要があるときに ajaxError がトリガーされるのを回避するにはどうすればよいですか? ちなみに、私は pjax を使用しています。

4

1 に答える 1

1

これは、jQuery が 404 をエラーとして処理するためです: https://github.com/jquery/jquery/blob/master/src/ajax.js#L613

あなたが与えている例では、サーバーはアプリケーションコントローラーで ActiveRecord::RecordNotFound 例外をキャッチし、#not_found の結果を返します。この jQuery に応答して、404 を検出し、ajaxError イベントを発生させます。

お役に立てれば。

于 2013-02-12T22:48:48.193 に答える