简体   繁体   中英

Laravel DataTables handle 401 Unauthorized error

I inherited a Laravel application that is using Yajra DataTables to display grid content in a page.

If Laravel's session expires, the DataTable will throw the following alert:

DataTables warning: table id=dataTableBuilder - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Viewing the Network tab in Chrome shows me that the AJAX response for the DataTable was a 401 Unauthorized. This is all expected behavior, but instead of displaying an arbitrary error to the user, I'd like to send the user to the login page with a message that says "your session timed out, please log in again." or something.

I can't figure out how to do that.

Traditional DataTables integrations allow me to pass an error handler to the AJAX response (ie {ajax: { error: function () {...} }} ), but there doesn't seem to be a way to do that with Laravel DataTables.

Laravel DataTables has an html() method that I can override like so:

public function html() {
    return $this->builder()
           ->ajax([
             error => ''
           ]);
}

But the ajax method on the builder doesn't allow me to pass a JavaScript handler to the error property.

Is there anyway to accomplish the force login when sessions time out?

Given the comment chain above, my suggestion would be to put a unique string in the error response, like:

code: 401

Then, use the global $.ajaxError to catch errors and do something different based on the response text:

$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    if (typeof settings === "string" && settings.indexOf('401') > -1) {
        //you can probably do something here
    }
});

You could probably even do this in a more efficient way as the 401 response type should be observable in one of the 4 properties (can't remember which)

An option more specific to DataTables that would not necessitate a global override is to use a function for $.fn.dataTable.ext.errMode

    $.fn.dataTable.ext.errMode = function (settings, tn, msg) {
      if (settings && settings.jqXHR && settings.jqXHR.status == 401) {
         // Handling for 401 specifically
      }
      // Handling for all other errors, this implements the DataTables default 
      // behavior of throwing an alert
      alert(msg)
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM