Ajax отлов ошибок

I would like to catch the error and show the appropriate message if the Ajax request fails.

My code is like the following, but I could not manage to catch the failing Ajax request.

function getAjaxData(id)
{
     $.post("status.ajax.php", {deviceId : id}, function(data){

        var tab1;

        if (data.length>0) {
            tab1 = data;
        }
        else {
            tab1 = "Error in Ajax";
        }

        return tab1;
    });
}

I found out that, «Error in Ajax» is never executed when the Ajax request failed.

How do I handle the Ajax error and show the appropriate message if it fails?

Peter Mortensen's user avatar

asked May 14, 2010 at 12:07

TTCG's user avatar

Since jQuery 1.5 you can use the deferred objects mechanism:

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });

Another way is using .ajax:

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});

Peter Mortensen's user avatar

answered May 14, 2010 at 12:11

choise's user avatar

choisechoise

24.7k19 gold badges75 silver badges131 bronze badges

4

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you’d like after the call. Deferred objects even allow you to attach multiple success and error handlers.

Example:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

Prior to jQuery 1.8, the function done was called success and fail was called error.

answered Aug 24, 2012 at 21:17

Michael Venable's user avatar

Michael VenableMichael Venable

5,0113 gold badges23 silver badges20 bronze badges

5

$.ajax({
  type: 'POST',
  url: 'status.ajax.php',
  data: {
     deviceId: id
  },
  success: function(data){
     // your code from above
  },
  error: function(xhr, textStatus, error){
      console.log(xhr.statusText);
      console.log(textStatus);
      console.log(error);
  }
});

answered May 14, 2010 at 12:12

jAndy's user avatar

jAndyjAndy

232k57 gold badges305 silver badges359 bronze badges

0

$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });

answered Feb 28, 2014 at 21:39

marknery's user avatar

marknerymarknery

1,5333 gold badges19 silver badges27 bronze badges

1

A simple way is to implement ajaxError:

Whenever an Ajax request completes
with an error, jQuery triggers the
ajaxError event. Any and all handlers
that have been registered with the
.ajaxError() method are executed at
this time.

For example:

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});

I would suggest reading the ajaxError documentation. It does more than the simple use-case demonstrated above — mainly its callback accepts a number of parameters:

$('.log').ajaxError(function(e, xhr, settings, exception) {
  if (settings.url == 'ajax/missing.html') {
    $(this).text('Triggered ajaxError handler.');
  }
});

Peter Mortensen's user avatar

answered May 14, 2010 at 12:12

karim79's user avatar

karim79karim79

340k67 gold badges414 silver badges406 bronze badges

2

You have to log the responseText:

$.ajax({
    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
  }
})
.done(
 function (data) {
  //your code
 }
)
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );
})

answered Sep 25, 2019 at 11:55

manolo's user avatar

In case you want to utilize .then() which has a subtle difference in comparison with .done() :

return $.post(url, payload)
.then(
    function (result, textStatus, jqXHR) {
        return result;
    },
    function (jqXHR, textStatus, errorThrown) {
        return console.error(errorThrown);
    });

answered Sep 13, 2020 at 22:57

panagiotis's user avatar

panagiotispanagiotis

1,5211 gold badge9 silver badges8 bronze badges

you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform…

quickie example:

ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
    alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );

answered Mar 2, 2020 at 22:01

Mark Giblin's user avatar

Mark GiblinMark Giblin

1,0862 gold badges13 silver badges20 bronze badges

2

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

$.ajax({
     url: 'does-not-exist.php',
     success: function(returnData){
         var res = JSON.parse(returnData);
     },
     error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }
});

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

  • jqXHR
  • textStatus
  • errorThrown

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

JQuery 3.0: The error, success and complete callbacks are deprecated.

Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.

An example of done and fail being used:

$.ajax("submit.php")
  .done(function(data) {
      //Ajax request was successful.
  })
  .fail(function(xhr, status, error) {
      //Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText
      alert('Error - ' + errorMessage);
})

Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.

Hopefully, you found this tutorial to be useful.

Documentation Menu

Many pages send AJAX requests to a server.
Because this relies on the cooperation of the server and the network between the client and the server,
you can expect these AJAX errors:

  • Your JavaScript program receives an error response instead of data;
  • Your program has to wait too long for the response. You can’t have the user wait indefinitely for some data to load.
  • Your program has to wait longer than expected for the response. You or your marketing department may decide to
    time out after 5 seconds, and that if responses take over 2 seconds to arrive you want to know about it.

This page shows how to implement AJAX error handling with JavaScript loggers that log to the server, so you find out about these issues.

Initial code without proper AJAX error handling

Below is a fairly typical AJAX call implemented with jQuery’s $.ajax:

var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
$.ajax(url, { "data": requestData, "type": "POST" }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message. }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

Step 1: Add timeout

The $.ajax method lets you set a timeout in milli seconds. When a timeout happens,

  • The fail callback is called, with errorThrown set to «timeout».
  • The request is aborted, meaning that even if the response arrives later on, your done callback is not called by jQuery.
var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
$.ajax(url, { "data": requestData, "type": "POST",     "timeout": 5000 }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message, or "timeout" in case of timeout. }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

Step 2: Log fatal message in case of error or timeout

When there is an AJAX error response or the AJAX request times out, you’ll
want to log as much information as you have, including the error message that jQuery gives you,
the url and the request data.

var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
$.ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message, or "timeout" in case of timeout.
JL().fatal({ "msg": "AJAX error response", "errorThrown": errorThrown, "url": url, "requestData": requestData }); }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

Step 3: Log warning message if AJAX response takes longer than expected

Record the time before making the AJAX call and compare that with the time
when the response is received to find out how long the user had to wait for the response.
Log a warning message if it took longer than expected.

var requestData = data to send to server;
var url = Url to send request to;
// Show spinner image
var msBeforeAjaxCall = new Date().getTime();
$.ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter
// Send warning log message if response took longer than 2 seconds var msAfterAjaxCall = new Date().getTime(); var timeTakenInMs = msAfterAjaxCall - msBeforeAjaxCall; if (timeTakenInMs > 2000) { JL().warn({ "msg": "AJAX response took long time", "timeTakenInMs": timeTakenInMs, "url": url, "data": data, "requestData": requestData }); } }) .fail(function (jqXHR, textStatus, errorThrown) { // Request failed. Show error message to user. // errorThrown has error message, or "timeout" in case of timeout.
JL().fatal({ "msg": "AJAX error response", "errorThrown": errorThrown, "url": url, "requestData": requestData }); }) .always(function(jqXHR, textStatus, errorThrown) { // Hide spinner image }

jQuery is the most awesome javascript library that exists. Every day, I’m finding new ways to leverage it and shorter, more efficient ways to get things done. But, while most things are easy to do, the solution is not always immediately evident. One of the things that took me a good while to figure out was how to gracefully handle AJAX errors. Anyone who’s worked with JSON requests and other AJAX calls knows that sometimes, that stuff just fails silently; you know something went wrong, but no errors were thrown. If it wasn’t for FireBug showing us 404 or 500 style errors, there’d be no evidence at all of these fails.

I’ve come up with a way to centralize my AJAX calls in a way that seemlessly handles all errors that occur either from the request connection or the JSON processing (ie. poorly formed JSON that cannot be converted back into Javascript data types). I’m not sure if this is the best of all ways, but I’m liking it. The whole concept rests on the fact that all of my system API (AJAX) calls return a uniform response with the following structure:

{
	SUCCESS: true,
	DATA: "",
	ERRORS: []
}

The Success property flags the request as having executed properly and returned the expected data. The Data property can be anything it needs to be. The Errors property is an array of any errors that need to be reported. It is only by requiring that all AJAX requests expect this that I can easily handle all errors.

In production, the following code would probably be part of some other object or integrated into the Javascript framework in a different way, but for this demo, I’m going to break out my AJAX request pipeline into its own class:

// Create an object to handle our AJAX.
function AJAX(){
	var objSelf = this;

	// This struct will cache the current XmlHTTP requests
	// so that we can reference them if a call fails.
	this.CurrentRequests = {};
}


// This handles the JSON request. This checks to see if the current
// request is already being processed and also handles any error
// wiring that is required.
AJAX.prototype.GetJSON = function( $1, $2, $3, $4 ){
	var objSelf = this;
	var strName = $1;
	var strURL = $2;
	var objOptions = $3;
	var fnCallback = $4;

	// Check to see if there are only three arguments. If there
	// are only 3, then the first one (name of request) which is
	// optional was not passed in. Shift the other arguments
	// to the appropriate variables.
	if (arguments.length == 3){

		// Name is not being used.
		strName = null;
		strURL = $1;
		objOptions = $2;
		fnCallback = $3;

	}

	// First, we have to check to see if this request is
	// already being processed. We don't want the user to
	// try and fire off multiple requests of the same type.
	// Of course, if the name is NULL, then don't worry.
	if (!strName || !this.CurrentRequests[ strName ]){

		// Store current request.
		this.CurrentRequests[ strName ] = true;

		// Make actual AJAX request.
		$.ajax(
			{
				// Basic JSON properties.
				url: strURL,
				data: objOptions,
				dataType: "json",

				// The success call back.
				success: function( objResponse ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to success handler.
					fnCallback( objResponse );
				},

				// The error handler.
				error: function( objRequest ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to fail handler.
					objSelf.AJAXFailHandler(
						objRequest,
						fnCallback
						);
				}
			}
			);

	} else {

		// This request is currently being processed.
		alert( "Request being processed. Be patient." );

	}
}


// This will handle all AJAX failures.
AJAX.prototype.AJAXFailHandler = function( objRequest, fnCallback ){
	// Since this AJAX request failed, let's call the callback
	// but manually create a failure response.
	fnCallback(
		{
			SUCCESS: false,
			DATA: "",
			ERRORS: [ "Request failed" ]
		}
		);
}

(I’m sorry the color coding doesn’t work for my Javascript files) There’s not a whole lot going on here, but let’s walk through it. First off, one thing you can do here is make sure that only one AJAX request (of a particular type) can be processed at a time. The GetJSON() method here can take 3 or 4 arguments. If you pass in the first, optional argument — the name of the request — the GetJSON() logic will make sure that it does not launch multiple instances of the same type of AJAX request at any one time. If you pass in only the three required fields, the GetJSON() method will allow parallel AJAX requests of the same type. You will see this in the demo below — I serialize my 200 requests but allow my 404 requests to happen in parallel.

The methodology that I use leverages the $.ajax() jQuery method. I used to just use the $.getJSON() method of the jQuery library, but the $.ajax() method gives us access to the Error call back method of the AJAX request. With this method and my unified AJAX response, handling errors is actually quite easy. All AJAX errors are piped through my AJAXFailHandler() method which creates a «fail» AJAX response (sets SUCCESS flag to false) and then manually executes the AJAX callback, passing in the fail response. This way, from the AJAX response handler’s point of view, it has no idea that anything has gone wrong — it only knows that it received a response object that was either flagged as a success or a failure.

Now, let’s take a look at the demo page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Handling AJAX Errors With jQuery</title>
	<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
	<script type="text/javascript" src="script.js"></script>
	<script type="text/javascript">

		// Initialize document.
		$(
			function(){
				var objAJAX = new AJAX();

				// Get reference to the three links.
				var j404 = $( "#error-404" );
				var jNoError = $( "#no-error" );

				// Set up 404 link.
				j404
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"does-not-exist.cfm",
								{},
								Do404RequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;

				// Set up no-error link.
				jNoError
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"NoErrorRequest",
								"200.cfm",
								{},
								NoErrorRequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;
			}
			);


		// I handle the 404 request repsonse.
		function Do404RequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "404 Error!" );
			}
		}


		// I handle the no-error request repsonse.
		function NoErrorRequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "No-Error Error!" );
			}
		}

	</script>
</head>
<body>

	<h1>
		Handling AJAX Errors With jQuery
	</h1>

	<p>
		<a id="error-404">404 Error</a> &nbsp;|&nbsp;
		<a id="no-error">Success</a>
	</p>

</body>
</html>

As you can see above, we are using jQuery to hook the links up to launch AJAX calls. Each of the two links — 404 and 200 responses — has its own response handler method. These methods, check to see if the response object was successful and just alerts the user. Notice that only the 200 style request passes in the name of the request, «NoErrorRequest»; this will ensure that the 200 style requests are serialized. The 404 style request, on the other hand, does not label its AJAX requests and therefore can make as many parallel requests as it likes.

I’m sure that I will continue to evolve the way I handle these situations over time, but so far, I have been really pleased with this methodology. It completely differentiates the two types of AJAX errors — logical vs. critical — and moves all critical error handling out of the business logic of the application.

If you are curious to see what is happening at the other end of the 200.cfm request, here is that template:

<!--- Create the response. --->
<cfset objResponse = {
	Success = true,
	Data = "Good request",
	Errors = []
	} />

<!--- Serialize the response. --->
<cfset strJSON = SerializeJSON( objResponse ) />

<!--- Get the binary response. --->
<cfset binJSON = ToBinary( ToBase64( strJSON ) ) />

<!--- Stream it back. --->
<cfheader
	name="content-length"
	value="#ArrayLen( binJSON )#"
	/>

<cfcontent
	type="text/json"
	variable="#binJSON#"
	/>

As you can see, it simply creates my unified AJAX response object and streams it back to the client.

Want to use code from this post?
Check out the license.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!

In this article I will explain how to handle errors and exceptions in jQuery AJAX calls and show (display) Custom Exception messages using jQuery Dialog.

There are two types of Exceptions which is caught by jQuery

1. When exception object is in the form of JSON object.

2. When exception object is in the form of plain text or HTML.

I will explain both the types with detailed explanation and also how to display the exception error details in both the cases.

WebMethod for testing both types

In order to test both the cases I have created the following WebMethod which simply tries to convert the received string value to integer.

[System.Web.Services.WebMethod]

public static void ValidateNumber(string number)

{

    int no = Convert.ToInt32(number);

}

1. When exception object is in the form of JSON object

In the following HTML Markup, I have created a simple form with a TextBox and a Button which prompts user to enter a Numeric value.

The value entered is passed to the WebMethod using a jQuery AJAX call where it is converts string value to integer.

If it is a valid number then an alert message is displayed inside the jQuery AJAX Success event handler and if an exception occurs in the WebMethod, the thrown exception is caught inside the jQuery AJAX Error event handler and which makes a call to the OnError JavaScript function which processes and displays the exception details.

<html xmlns=»http://www.w3.org/1999/xhtml»>

<head runat=»server»>

    <title></title>

    <style type=»text/css»>

        body { font-family: Arial; font-size: 10pt; }

        #dialog { height: 600px; overflow: auto; font-size: 10pt !important; font-weight: normal !important; background-color: #FFFFC1; margin: 10px; border: 1px solid #ff6a00; }

        #dialog div { margin-bottom: 15px; }

    </style>

</head>

<body>

    <form id=»form1″ runat=»server»>

        <u>1: When exception object is in the form of JSON object</u>

        <br/>

        <br/>

        Enter Number:

        <input id=»txtNumber1″ type=»text»/>

        <input id=»btnValidate1″ type=»button» value=»Validate»/>      

        <div id=»dialog» styledisplay: none»></div>

        <script type=»text/javascript» src=»http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js»></script>

        <script src=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js» type=»text/javascript»></script>

        <link href=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css»

            rel=»stylesheet» type=»text/css»/>

        <script type=»text/javascript»>

            $(function () {

                $(«#btnValidate1»).click(function () {

                    var number = $(«#txtNumber1»).val();

                    $.ajax({

                        type: «POST»,

                        url: » Default.aspx/ValidateNumber»,

                        data: ‘{number: «‘ + number + ‘»}’,

                        contentType: «application/json; charset=utf-8»,

                        dataType: «json»,

                        success: function (r) {

                            alert(«Valid number.»);

                        },

                        error: OnError

                    });

                });

            });

            function OnError(xhr, errorType, exception) {

                var responseText;

                $(«#dialog»).html(«»);

                try {

                    responseText = jQuery.parseJSON(xhr.responseText);

                    $(«#dialog»).append(«<div><b>» + errorType + » « + exception + «</b></div>»);

                    $(«#dialog»).append(«<div><u>Exception</u>:<br /><br />» + responseText.ExceptionType + «</div>»);

                    $(«#dialog»).append(«<div><u>StackTrace</u>:<br /><br />» + responseText.StackTrace + «</div>»);

                    $(«#dialog»).append(«<div><u>Message</u>:<br /><br />» + responseText.Message + «</div>»);

                } catch (e) {

                    responseText = xhr.responseText;

                    $(«#dialog»).html(responseText);

                }

                $(«#dialog»).dialog({

                    title: «jQuery Exception Details»,

                    width: 700,

                    buttons: {

                        Close: function () {

                            $(this).dialog(‘close’);

                        }

                    }

                });

            }

        </script>

    </form>

</body>

</html>

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

2. When exception object is in the form of HTML or plain text

The second case is similar to the first one. In order to receive a Non-JSON response I have just set incorrect WebMethod name in the jQuery AJAX so that it generates an error.

<html xmlns=»http://www.w3.org/1999/xhtml»>

<head runat=»server»>

    <title></title>

    <style type=»text/css»>

        body { font-family: Arial; font-size: 10pt; }

        #dialog { height: 600px; overflow: auto; font-size: 10pt! important; font-weight: normal !important; background-color: #FFFFC1; margin: 10px; border: 1px solid #ff6a00; }

        #dialog div { margin-bottom: 15px; }

    </style>

</head>

<body>

    <form id=»form1″ runat=»server»>

        <u>2: When exception object is in the form of HTML or plain text</u>

        <br/>

        <br/>

        Enter Number:

        <inputi d=»txtNumber2″ type=»text»/>

        <input id=»btnValidate2″ type=»button» value=»Validate»/>

        <div id=»dialog» styledisplay: none»></div>

        <script type=»text/javascript» src=»http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js»></script>

        <script src=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js» type=»text/javascript»></script>

        <link href=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css»

            rel=»stylesheet» type=»text/css»/>

        <script type=»text/javascript»>

            $(function () {

                $(«#btnValidate2»).click(function () {

                    var number = $(«#txtNumber2»).val();

                    $.ajax({

                        type: «POST»,

                        url: «Default.aspx/UnknownMethod»,

                        data: ‘{number: «‘ + number + ‘»}’,

                        contentType: «application/json; charset=utf-8»,

                        dataType: «json»,

                        success: function (r) {

                            alert(«Valid number.»);

                        },

                        error: OnError

                    });

                });

            });

            function OnError(xhr, errorType, exception) {

                var responseText;

                $(«#dialog»).html(«»);

                try {

                    responseText = jQuery.parseJSON(xhr.responseText);

                    $(«#dialog»).append(«<div><b>» + errorType + » « + exception + «</b></div>»);

                    $(«#dialog»).append(«<div><u>Exception</u>:<br /><br />» + responseText.ExceptionType + «</div>»);

                    $(«#dialog»).append(«<div><u>StackTrace</u>:<br /><br />» + responseText.StackTrace + «</div>»);

                    $(«#dialog»).append(«<div><u>Message</u>:<br /><br />» + responseText.Message + «</div>»);

                } catch (e) {

                    responseText = xhr.responseText;

                    $(«#dialog»).html(responseText);

                }

                $(«#dialog»).dialog({

                    title: «jQuery Exception Details»,

                    width: 700,

                    buttons: {

                        Close: function () {

                            $(this).dialog(‘close’);

                        }

                    }

                });

            }

        </script>

    </form>

</body>

</html>

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

Parsing the received Exception response using jQuery

Here I am explaining the details of the OnError JavaScript function which is called by the Error event handler in both the above case.

This function accepts the following three parameters

xhr – It is the error response object.

errorType – It describes the type of error.

exception – It contains the title of the exception occurred.

Inside this function, I have placed a TRY CATCH block and within the TRY block, the Exception received is parsed to a JSON object and then the details of the exception are displayed using jQuery Dialog Modal Popup.

If an error occurs during the process of parsing the JSON string, it means it is a Non-JSON response i.e. HTML or plain text and then it is handled inside the CATCH block where I am displaying the exception directly without any processing.

function OnError(xhr, errorType, exception) {

    var responseText;

    $(«#dialog»).html(«»);

    try {

        responseText = jQuery.parseJSON(xhr.responseText);

        $(«#dialog»).append(«<div><b>» + errorType + » « + exception + «</b></div>»);

        $(«#dialog»).append(«<div><u>Exception</u>:<br /><br />» + responseText.ExceptionType + «</div>»);

        $(«#dialog»).append(«<div><u>StackTrace</u>:<br /><br />» + responseText.StackTrace + «</div>»);

        $(«#dialog»).append(«<div><u>Message</u>:<br /><br />» + responseText.Message + «</div>»);

    } catch (e) {

        responseText = xhr.responseText;

        $(«#dialog»).html(responseText);

    }

    $(«#dialog»).dialog({

        title: «jQuery Exception Details»,

        width: 700,

        buttons: {

            Close: function () {

                $(this).dialog(‘close’);

            }

        }

    });

}

Demo

Downloads

Понравилась статья? Поделить с друзьями:
  • Ajax http ошибка 500
  • Ajax error вывод ошибок
  • Ajax 502 ошибка
  • Al006 ошибка delta
  • Aisino v71 ошибка печати