Wednesday, February 26, 2014

How to return error messages in AJAX calls

In AJAX calls exception can occur mainly due to 1) communication error 2) server error. We will look at how to handle these exceptions

Given below is a simple AJAX application – both client code and server handler

JS Code
  <script>

        $.ajax({ url: "NewRequestHandler.aspx?val1=10&val2=11",
            success: function (data) {//Get result object from server
                alert(data.Result);
                if (data.Error!= null) {
                    alert(data.Error); //Get error returned by server
                }
            },
error: function (xhr, errorType, exception) { //Triggered by communication error, like http 404  etc
                alert(xhr.responseText);
                return false;
            }
        });

    </script>

Server Code
public class NewRequestHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //this object will be returned in the response
            NewData data = new NewData();
            try
            {
                int val1 = Int32.Parse(context.Request.QueryString["val1"]);
                int val2 = Int32.Parse(context.Request.QueryString["val2"]);
                data.Result = val1 + val2;
            }
            catch (Exception ex)
            {
                //capture any exceptions and add it to the response object
                data.Error = ex.Message;
            }
            //convert the object to JSON and return
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            context.Response.ContentType = "text/json";
            context.Response.Write(serializer.Serialize(data));
        }
        public bool IsReusable
        {
            get { return true; }
        }
        public class NewData
        {
            public int Result;
            public string Error;
        }
    }

Any error in communicating with the server will be captured by the below line of code in JS

error: function (xhr, errorType, exception) { //Triggered by communication error, like http 404  etc

Errors occurring in server is captured by the C# and returned in the JSON object. JS code can check for this ‘error’ property to display exceptions from server

if (data.Error!= null) {
                    alert(data.Error); //Get error returned by server
                }

No comments: