The commoditization of technology has reached its pinnacle with the advent of the recent paradigm of Cloud Computing. Infosys Cloud Computing blog is a platform to exchange thoughts, ideas and opinions with Infosys experts on Cloud Computing

« Windows Azure Table storage- How to handle CAUTIOUSLY nullable data types | Main | My road trip for the Windows Azure Spring Release »

Providing user defined status code and message in asp.net MVC action and handling it in jQuery

Suppose in an asp.net mvc application, from a controller action we need to return user defined status code and message instead of general http status codes like 200, 401, 500, etc.  Example of such scenario is when we want to return some application specific validation error message and code. There quite a few ways but among those, I liked the below two options because here we may avoid explicitly throwing and catching exception.

One point I would like to mention is, whenever we provide any status code (say 2001) other than those from 200 series, it is considered as erroneous response.

Approach:

Server Side Code:

Once any validation is done and any specific error message is to be returned, set the http response status code as:

public JsonResult SomeAction()

{

                JsonResult result = new JsonResult();

                ...

                //Once any validation is done and error condition is identified

                if(someValidationError)

                {

                                Response.StatusCode = 2000;

                                result= Json("user defined error", JsonRequestBehavior.AllowGet);

                                //or any user define class in the JSON result holding the error message along with any other info to be conveyed

                }

                return result;

}

 

Or

public JsonResult SomeAction()

{

                JsonResult result = new JsonResult();

                ...

                //Once any validation is done and error condition is idenfied

                if(someValidationError)

                {

                                Response.StatusCode = 2000;

                                Response.Write("user defined error");

                                result= null;

                }

                return result;

}

 

Note- If simply the Response.StatusDescription is edited, the .net framework considers it as a "internal server error" and the provided StatusCode will get overridden by 500

 

Client Side code:

 

In the client side code, e.g. a Javascript function calling the above controller action:

 

function GetData() {

                $.getJSON('/controller/SomeAction', null, function (data) {

                //if the execution happened without any error or if no user defined StatusCode is assigned

                //i.e. in case of Success, this part of code is executed by default

                })

                   //in case of error or explicit assignment of StatusCode

                .error(function (jqXhr, statusText, errorThrown) {

        alert("in error");

        alert(jqXhr.status); //- the custom code e.g. 2000

        alert(jqXhr.statusText); //or  alert(statusText); - error

        alert(jqXhr.responseText); // - the custom message or the serialized JSON result

       

       // in case responseText has serialized JSON object then de-serialize it as

       // var data = $.parseJSON(jqXhr.responseText)

                                           //and then bind the information to the right control

 

                })

 

                .complete(function () {

        alert("in complete");

        //any common execution i.e. for both success and error

                });            //';' to be provided to the last event, i.e. if complete is not used then ;  should be at the end of error event above

}

Happy coding...

Comments

Nice article, it helped me alot in creating custom codes

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

Please key in the two words you see in the box to validate your identity as an authentic user and reduce spam.