Introduction
Since SharePoint’s entry into the Content Management Field, developers had to interact with it using the server side object model. Though Out of the box web services were available it had its own limited development capability. With the introduction of client side object model things became much easier as developers could now interact with SharePoint remotely. Client side object model comes in 3 flavors,
- .Net managed client side object model(CSOM)
- JavaScript object model(JSOM)
- Silverlight client side object model
.Net client side object model is used to access SharePoint remotely from a console application and provides strongly-typed representation of SharePoint objects using the client library Microsoft.SharePoint.Client.dll . JavaScript object model on the other hand is used to access and interact with SharePoint from within the client browser in an asynchronous fashion. We can make use of Content Editor Web part or SharePoint apps to directly communicate with SharePoint by making use of JSOM.JSOM particularly makes use of the SP.js library to handshake with SharePoint server. Silver light has become deprecated and so is Silverlight Client Object Model.
JSOM Working
- MicrosoftAjax.js- Usually loaded by ScriptResource.axd
- SP.Runtime.js- Loaded from the LAYOUTS folder
- SP.JS- Loaded from the LAYOUTS folder

Script on Demand
SP.SOD.executeOrDelayUntilScriptLoaded
- SP.SOD.executeOrDelayUntilScriptLoaded(getWeb, 'SP.js');
- function getWeb() {
- // Get the current client context and Web instance.
- var clientContext = new SP.ClientContext.get_current();
- var oWeb = clientContext.get_web();
- }
SP.SOD.executeFunc
- Sp.js- the script file that will be invoked and loaded to the page. It can be any file
- SP.ClientContext- The main object within the script file that will be used. It can be kept null.
- retrieveListItems- The function to run after the script files are loaded to the page.
JSOM Structure
- $(document).ready(function() {
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
- });
- var collListItem;
- function retrieveListItems() {
- //Get client context,web and Listobject
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- var oList = oWeb.get_lists().getByTitle('Employees');
- //Get list item collection
- collListItem = oList.getItems(SP.CamlQuery.createAllItemsQuery());
- //Load the client context and execute the batch
- clientContext.load(collListItem);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
- function QuerySuccess() {
- //Create enumerator object and loop through the collection
- var listItemEnumerator = collListItem.getEnumerator();
- while (listItemEnumerator.moveNext()) {
- var oListItem = listItemEnumerator.get_current().get_item('Name');
- console.log("Name : " + oListItem);
- }
- }
- function QueryFailure() {
- console.log('Request failed' + args.get_message());
- }
- As a first step, get the current context by calling SP.ClientContext.get_Current method. Since JSOM is running in the context of the browser we cannot impersonate the user . Only way to change the user context is to run the client browser in the required user’s credential.
- Once the context object is created, make a call to get the current web
var oWeb = clientContext.get_web();
- The get_lists() method of the web object returns all the list collection present in the current web. Applying getByTitle () on the list collection fetches the specific Employees list. var oList = oWeb.get_lists().getByTitle('Employees');
- Now, call getItems method on the list object to return all the itemscollListItem = oList.getItems(SP.CamlQuery.createAllItemsQuery());
- The context object provides the load method which is responsible for loading objects and collections from the server. Whatever object is passed into the load method is populated and can be used in the subsequent call back function.
- If you want to work with the child properties of an object, it must be loaded by calling ‘clientcontext.load(object)’ followed by the executequeryasync call .Otherwise, you will generate an exception such as the following,“The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.”
- JSOM provides the flexibility to execute the requests in batches. Thus each request to create a web object, create a list from the web object won’t be send as separate requests to the server. Instead all the requests will be batched together and send to client.svc upon calling the executequeryasync call. In the above example, we are making calls on the context, web, and list objects but cannot work with the objects’ child properties. Only when the call to ExecuteQueryAsync method is made, an XML request is generated and then sent to the server’s client.svc for processing. As part of ExecuteQueryAsync you have to provide two callback – a success and failure call back. These methods specify how to proceed when the request is processed.
- Depending on the Success/ Failure of the executeQueryAsync call, control will be passed to the appropriate call back function. From within the function we can then access properties of the loaded object. For instance in the above example, the loaded object is the list item collection which can be iterated by instantiating an enumerator object as shown below,
- var listItemEnumerator = collListItem.getEnumerator();
- while (listItemEnumerator.moveNext()) {
- var oListItem = listItemEnumerator.get_current().get_item('Name');
- console.log("Name : " + oListItem );
- }
JavaScript object model is an asynchronous programming model that enables communication with SharePoint in the client side. As with any programming constructs JavaScript object model also has exception handling techniques. JavaScript provides native try/catch to handle exceptions. Though JSOM is based on JavaScript using Try/Catch will not really do exception handling in JSOM. This is because of the asynchronous nature of JSOM. In JSOM all the operations are send as a batch to ‘client.svc’ WCF service in the server that would process the request.
SharePoint however provides an exception handling mechanism similar to JavaScript try/catch of the format startTry() and startCatch() . Its implementation is similar to try/catch.
The main object that handles the exception in JSOM Is called ‘ExceptionHandlingScope’.It provides the below methods to perform exception handling.
Exception Handling
- startScope
- startTry
- startCatch
- startFinally
Let’s see how it works,
As with any JSOM implementation we create the starting object which is client context. After that we create an exception handling scope object using the client context. Once the exception handling scope object is created we call its startScope method. This method indicates that the entire code within the block will be eligible for exception handling.
Once the exception handling scope starts we can initiate the try block using the startTry method. Any code written within the startTry method will be checked for exceptions and in the event of an exception the control will be passed to the exception handling block which is the catch block. The code block that began with startTry will be ended using the dispose method. The exception handling block that will be called in case of any error in the try block is the catch block which is instantiated using startCatch method. Within this block we can add the code that will resolve the issue that happened in the try block. Similar to try block catch block will also be ended using the dispose method.
The last code block of the exception handling paradigm is the finally block which is instantiated using the startFinally () method. This block will have all the code that needs to be run regardless of if an error occurs. The dispose method can be called to indicate the end of the finally block.
We can see how exception handling paradigm can be used in a real word scenario. Let’s say, we are trying to update a list which does not exist in SharePoint environment. This will ideally throw an exception as the object is not present. We will write the erroneous list update code in try block and handle the exception in the catch block by creating the list. In the finally block we will again try to update the list. This time the list will be updated without any exceptions.
Full Script
The full code for implementing exception handling is shown below,
Internal Implementation

- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- $(document).ready(function() {
- SP.SOD.executeOrDelayUntilScriptLoaded(CheckandCreateList, "sp.js");
- });
- function CheckandCreateList() {
- //Get the client context and web object
- var clientContext = new SP.ClientContext.get_current();
- var oWeb = clientContext.get_web();
- //Create exception handling scope and start the scope
- var exceptionScope = new SP.ExceptionHandlingScope(clientContext);
- var startScope = exceptionScope.startScope();
- //Instantiate Try Scope
- var tryScope = exceptionScope.startTry();
- //Add the code to update the list that does not exist which will cause error.
- var oList = clientContext.get_web().get_lists().getByTitle("ExceptionList");
- oList.set_description("Updated Description");
- oList.update();
- //Dispose the scope
- tryScope.dispose();
- //Instantiate Catch Scope
- var catchScope = exceptionScope.startCatch();
- //Within the catch scope write the JSOM code to create new list which will resolve the error.
- var newListCreationInfo = new SP.ListCreationInformation();
- newListCreationInfo.set_title("ExceptionList");
- newListCreationInfo.set_description("Catch Updated Description");
- newListCreationInfo.set_templateType(SP.ListTemplateType.genericList);
- clientContext.get_web().get_lists().add(newListCreationInfo);
- //Dispose the Catch Scope
- catchScope.dispose();
- //Instantiate the Finally Scope
- var finallyScope = exceptionScope.startFinally();
- //Update the newly created List
- var oList = clientContext.get_web().get_lists().getByTitle("ExceptionList");
- oList.set_description("Finally Updated Description");
- oList.update();
- //Dispose finallyScope
- finallyScope.dispose();
- // Dispose startScope
- startScope.dispose();
- //Execute the batch
- clientContext.executeQueryAsync(Success, Failure);
- }
- function Success() {
- console.log("The list has been created successfully.");
- }
- function Failure(sender, args) {
- console.log('Request failed - ' + args.get_message());
- }
- </script>


Summary
Thus we saw the basics of JavaScript Object Model implementation and exception handling in SharePoint.

Prasanna MuraliPosted Sep 5, 2016, 11:06 AM
Nice post......