Monthly Archives: April 2013

Object Reflection In JavaScript

Reflection is a powerful technique that I’ve used a lot in C#. On several occasions I’ve found some uses for this technique in JavaScript too. Most recently, I was writing a test harness for a RESTFul web service to allow our QA folks a easy way to test it. Typically, when I’m writing these kinds of things I have a couple objectives in mind.

First, I don’t want to turn the testing tool into a maintenance item. That is, if there are updates to the software being tested (a web service in this case) I don’t want to have to update the tool.

Second, I don’t want to add another uncontrolled variable to the testing.   Meaning, I don’t want the testing tool to require extensive QA or to create a layer of possible bugs to be validated anytime QA finds an issue with the software being tested.

Finally, I don’t want to spend a lot of time on it and I’d like to reuse it. It’s an internal tool that is usually being used by a semi-technical person and has a very specific purpose, being pretty isn’t one of them. And, if I can use it again, for another web service in this case, double bonus!

In the case of the RESTFul Web Service testing tool I accomplished this in two ways.

First, I build the inputs for the service by parsing the web service schema (.xsd) dynamical. This way, if new inputs are added I don’t have to update the testing tool. I probably write a post on that part another day.

Second, I output the results (which are returned in JSON) to a web page using reflection after the JSON object is parsed to a JavaScript object.

Here is an example of how I do it:

Consider the following object. It has a set of properties, a nested object, and a function.

var obj = new Object;
obj.FirstName = “John”;
obj.LastName = “Smith”;
obj.FullName = “John Smith”;
obj.Address = “Main Street”;
obj.Phone = “999-999-9999”
obj.GetName = (function () {});
obj.History = new Object();
obj.History.PreviousAddress = “South Street”;
obj.History.PreviousPhone = “888-888-8888”;

All I want to do is print each property and it’s value to the screen. And, if there is a nested object I want to print it’s properties too. This will allow the return results to be validated.

To do this I use a script like this:

function DisplayObjectProperties(obj) {
for (prop in obj) {
var text = “”
if(typeof obj[prop] != “function” && typeof obj[prop] != “object”){
text = prop + “: ” + obj[prop];
}
else if (typeof obj[prop] === “object”) {
DisplayObjectProperties(obj[prop])
}
$(“body”).append(“<div>”+ text + “</div>”);
}
}

Nothing too much going on here, just a loop through the object and appending each property name and it’s value to an html element.  The important thing is to test the type, so you can handle nested objects, arrays, functions, etc however you might want to.  In my case, if there is a nested object I want to display it’s properties too.  I do that with a recursive call to the function passing the nested object.

Call it:  Just pass the object to the function it will do the rest.

DisplayObjectProperties(obj);

Results:

FirstName: John
LastName: Smith
FullName: John Smith
Address: Main Street
Phone: 999-999-9999
PreviousAddress: South Street
PreviousPhone: 888-888-8888
Advertisements

Returning Errors in a WCF RESTful Web Service

While writing web services I’ve used several different methods for returning errors. A very common method is to return null or if the response is a string return the word error or a message stating there was an error. That works, but I’ve never really been a big fan.

Example:

public object GetSomething(string param)
{
try
{
var returnObject = new object() = some code here
return returnObject;
}
catch (Exception ex)
{
return null;
  or
return new object();
 or
 some variation;
}

}

This method doesn’t really seem to comply with best practices for being RESTful or for OOP. It gets you by, but it’s kind of smelly.

More recently, especially with RESTful WCF Web Services that are returning complex objects, I’ve added DataMembers to the DataContract that include an error Boolean and error message along with the object(s) I’m returning as a DataMember.

Example:

[DataContract(Name=”returnObject”)]
public class returnSomeObjects
{
[DataMember]
public IList <someObject> { get; set; }
[DataMember]
public bool Error { get; set; }
[DataMember]
public string Message { get; set; }
}

Then in the error handling above:

catch (Exception ex)
{
return new returnObjects() {Error = true, Message = “ex.Message”};
}

I like this method more because it always returns the same object and the calling process can make a decision based on error being true or false. Even if you don’t have complete control of the returning object(s); for instance when wrapping a legacy class library with a service, you can just make the object a DataMember on the DataContract and away you go.

The problem with this method is the http response is a 200 ok, even though an error occurred. So, it’s not as smelly, but still not the best practice. Recently I’ve begun to favor a more organic approach. Something that is more RESTful in nature, that is modifying the http status code to reflect that an error has occurred.

Example:
catch (Exception ex)
{
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = “A unexpected error occurred!”;
}

You could evaluate the exception and return codes based on certain situations, I use the above for unexpected errors. You could also make the response.StatusDescription the exception message. The calling process can now key off of the http status code and handle the situation as required by it’s own system and rules.

You might ask, why modify the status code? If you just simply throw the error you achieve something very similar, that is a HTTP status code other than 200 ok. The issue, for me at least, is you get a 400 bad request. Which is a little misleading to the caller and not exactly true if somewhere in my data or logic layer an error has occurred.

So I like to add a little control. You can evaluate for invalid parameters or data and still return the 400 bad request when appropriate, but for unexpected errors, I like returning the 500 Internal Server Error.

I should mention I’m using this for internal web services so I do have more latitude in what I show to the calling processes and systems, however, I see no reason why using standard http response codes would be a problem in a public API.

Additionally, this method adds more consistency to what a calling process will get when errors occur. For example, with the previous methods if your service is unreachable they would get a different response then if it is reached and a custom error is returned. In other words, they can always evaluate the response codes that are native to http giving you a more RESTful response.


%d bloggers like this: