javascriptjqueryajaxerror-handlingblockui

Avoid code pausing/freezing on javascript error in jQuery blockUI


Let me try to make some sense...

We're blocking the UI using jQuery block UI plugin

$(document).ajaxStart(function() {
  $.blockUI({
    message: '<h4><i class="fa fa-circle-o-notch fa-spin fa-fw"></i> loading...</h4>'
  })
}).ajaxStop($.unblockUI);

Sometimes, when the code throws some error:

JSON error on console

The loading message on the freezed screen doesn't vanishes:

loading message on the freezed screen

The reason is:

  1. When the ajaxStart() starts, the $.blockUI() gets invoked.

  2. And before the ajaxStart() could successfully finish executing, it encounters an error.

  3. ajaxStop() is never reached and the UI is never unblocked ($.unblockUI)

So, what I'm looking for is a way to show some custom message when there is some error between ajaxStart() and ajaxStop(). Instead of code pausing/freezing on javascript error.

Also, when I try @Raghav's suggestion, it doesn't un-freezes the screen.

$(document).ajaxStart(function() {
  $.blockUI({
    message: '<h4><i class="fa fa-circle-o-notch fa-spin fa-fw"></i> loading...</h4>'
  })
  throw Error;
  debugger;
}).ajaxStop($.unblockUI).ajaxError($.unblockUI);

Doesn't it make sense?


Solution

  • Have you tried handling errors using ajaxError()

    See: https://api.jquery.com/ajaxError/

    $(document).ajaxError(function() {
       $.unblockUI();
       // Display error message here
       alert('Some error message');
    }); 
    $(document).ajaxStop(function() {$.unblockUI();});
    $(document).ajaxStart(function() {
      $.blockUI({
        message: '<h4><i class="fa fa-circle-o-notch fa-spin fa-fw"></i>loading...</h4>'
      })
    });
    

    You can also fetch the error message. See the documentation for details.

    $(document).ajaxError(function( event, jqxhr, settings, thrownError ) {
    
       $.unblockUI();
       console.log(event, jqxhr, settings, thrownError);
    });