How to Implement Exception Handling in jQuery While Calling Web Service






If you are using an Ajax Web service call in jQuery and if you make a small syntax or typo mistake then it will be tedious to determine the exact root cause of the problem. Even if you debug in a browser it will not show the exact error message.

But if you write proper exception handling code in the jQuery web service call then you can easily determine the exact problem in your code.

Here we can implement exception handling in two ways.

Approach 1:

  1. error: function (XMLHttpRequest, textStatus, errorThrown) {  
  2.                            var err = eval("(" + XMLHttpRequest.responseText + ")");  
  3.                            alert(err.Message)  
  4.                        } 

Approach 2:

  1. error: function (response) {  
  2.                            var r = jQuery.parseJSON(response.responseText);  
  3.                            alert("Message: " + r.Message);  
  4.                            alert("StackTrace: " + r.StackTrace);  
  5.                        } 

The complete jQuery code will be like this:

  1. <script type="text/javascript">  
  2.        $(function () {  
  3.            $("#txtEmpName").autocomplete({  
  4.                source: function (request, response) {  
  5.                    var param = { empName1: $('#txtEmpName').val() };  
  6.                    $.ajax({  
  7.                        url: "WebForm1.aspx/GetEmpNames",  
  8.                        data: JSON.stringify(param),  
  9.                        dataType: "json",  
  10.                        type: "POST",  
  11.                        contentType: "application/json; charset=utf-8",  
  12.                        dataFilter: function (data) { return data; },  
  13.                        success: function (data) {  
  14.                            response($.map(data.d, function (item) {  
  15.                                return {  
  16.                                    value: item  
  17.                                }  
  18.                            }))  
  19.                        },  
  20.    
  21.                        //Approach 1  
  22.    
  23.                        error: function (XMLHttpRequest, textStatus, errorThrown) {  
  24.                            var err = eval("(" + XMLHttpRequest.responseText + ")");  
  25.                            alert(err.Message)  
  26.                             
  27.                        }  
  28.    
  29.                        //Approach 2  
  30.    
  31.                        //error: function (response) {  
  32.                        //    var r = jQuery.parseJSON(response.responseText);  
  33.                        //    alert("Message: " + r.Message);  
  34.                        //    alert("StackTrace: " + r.StackTrace);  
  35.                        //}  
  36.                    });  
  37.                },  
  38.                minLength: 2 //This is the Char length of inputTextBox  
  39.            });  
  40.        });  
  41.    </script> 

The code behind file is like this:

  1. [WebMethod]  
  2.       public static List<string> GetEmpNames(string empName)  
  3.       {  
  4.           List<string> Emp = new List<string>();  
  5.           string query = string.Format("SELECT EmpName FROM tblEmp WHERE EmpName LIKE '%{0}%'", empName);  
  6.           using (SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True"))  
  7.           {  
  8.               using (SqlCommand cmd = new SqlCommand(query, con))  
  9.               {  
  10.                   con.Open();  
  11.                   SqlDataReader reader = cmd.ExecuteReader();  
  12.                   while (reader.Read())  
  13.                   {  
  14.                       Emp.Add(reader.GetString(0));  
  15.                   }  
  16.               }  
  17.           }  
  18.           return Emp;  
  19.       } 

Note: If you observe in the code above I have given the parameter as EmpName but I am passing the parameter as empName1 to generate the exception. Now if you see the preceding exception then you can easily analyze it and determine the exact problem.

If you know a better approach then let me know.

Up Next
    Ebook Download
    View all
    Learn
    View all