How to handle a specific HTTP error for all AJAX calls?

I have a web application requesting and sending data through AJAX, and as a response, my server side sends HTTP status codes depending on the situation. so, for example, if a user tries to log in during registration, I will probably return his 400 HTTP status code . And in the end I process it with a warning, etc.

But handling these HTTP status codes is getting too heavy since I use AJAX a lot. this means that I will process the HTTP status code several times with each AJAX request, which will lead to duplicate code and bad practice.

So, what I'm looking for is a way to handle all these errors in one place, so I just process all the 400 , 401 tags, etc. with the same code.

What am I doing now:

Manual error handling for each AJAX call. Using statusCode in $.ajax() .

  statusCode: { 500: function(data) { alert('Some friendly error message goes here.'); } 

It seems to me that this is too much, as my web application develops, and when I create more ajax calls. I will repeat this piece of code again and again.

Currently, the only idea I have in mind is to create a function that will work on top of AJAX, for example:

  function doAjax(type,url, data, moreVars) { //this function is just a SIMPLE example, could be more complex and flexible. $.ajax({ type: type, url: url, data: data, moreOptions:moreVars, //now handling all status code. statusCode: { //handle all HTTP errors from one place. } }); } doAjax("POST", 'mydomain.com/login.php', dataObj); 
+6
source share
1 answer

You can use $.ajaxSetup() to register global error state handlers.

Description Set default values ​​for future Ajax requests.

Example:

 $.ajaxSetup({ statusCode: { 500: function(data) { alert('Some friendly error message goes here.'); } } }); 
+11
source

Source: https://habr.com/ru/post/921583/


All Articles