Jquery: common place to handle all ajax request errors

A lot of time we write similar kind of code to handle errors of an ajax request. And changing logic at every place could be a challenge. Jquery has method to handle this

$.ajaxSetup({
	// Define a global error handler
	error: function (xhr, textStatus, errorThrown) {
		if (xhr.status === 401) {
			// Handle unauthorized (e.g., redirect to login page)
			window.location.href = '/login';
		} else if (xhr.status === 403) {
			// Handle forbidden access (e.g., show an error message)
			alert('Access forbidden.');
		} else {
			// Handle other errors (e.g., show a generic error message)
			alert('An error occurred: ' + xhr.statusText);
		}
	}
});

similar to this you can also write your common success method as well. You can also use beforeSend method to modify all the request at common place as well

Leave a Reply

Your email address will not be published. Required fields are marked *