JavaScript Object Model Exception Handling In SharePoint

JavaScript Object Model is an asynchronous programming model, which enables the communication with SharePoint in the client side Browser. As with any programming constructs, JavaScript Object Model also has the exception handling techniques. JavaScript provides native try/catch to handle the 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 sent as a batch to ‘client.svc’ WCF Service in the Server, which would process the request.

Exception Handling Scope

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, which handles the exception in JSOM Is called ‘ExceptionHandlingScope’. It provides the methods, given below, to perform an exception handling.

  • startScope
  • startTry
  • startCatch 
  • startFinally

Let’s see, how it works:

Internal Implementation

With any JSOM implementation, we create the base object, which is the client context. Afterwards, we create an exception handling scope object, using the client context. Once the exception handling scope object is created, we call it’s ‘startScope’ method. This method indicates that the entire code within the block will be eligible for an exception handling. Let’s take an example code, which will try to update a list, which does not exist. This would generate an exception, which will be handled by the exception handling scope.

code

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, which began with ‘startTry’ will be ended, using the dispose method. The exception handling block, which 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, which 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  finally a block, which is instantiated, using the ‘startFinally ’ method. This block will have all the code, which needs to be run, regardless of an error, which might occur. The dispose method can be called to indicate the end of the finally block.

We can see, how an exception handling paradigm can be used in a real word scenario. Let’s see, 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.

Script

The full script for the exception handling scope implementation is shown below:

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2. <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         SP.SOD.executeOrDelayUntilScriptLoaded(CheckandCreateList, "sp.js");  
  5.     });  
  6.   
  7.     function CheckandCreateList() {  
  8.         //Get the client context and web object   
  9.         var clientContext = new SP.ClientContext.get_current();  
  10.         var oWeb = clientContext.get_web();  
  11.         //Create exception handling scope and start the scope  
  12.         var exceptionScope = new SP.ExceptionHandlingScope(clientContext);  
  13.         var startScope = exceptionScope.startScope();  
  14.         //Instantiate Try Scope  
  15.         var tryScope = exceptionScope.startTry();  
  16.         //Add the code to update the list that does not exist which will cause error.  
  17.         var oList = clientContext.get_web().get_lists().getByTitle("ExceptionList");  
  18.         oList.set_description("Updated Description");  
  19.         oList.update();  
  20.         //Dispose the scope  
  21.         tryScope.dispose();  
  22.         //Instantiate Catch Scope  
  23.         var catchScope = exceptionScope.startCatch();  
  24.         //Within the catch scope write the JSOM code to create new list which will resolve the error.  
  25.         var newListCreationInfo = new SP.ListCreationInformation();  
  26.         newListCreationInfo.set_title("ExceptionList");  
  27.         newListCreationInfo.set_description("Catch Updated Description");  
  28.         newListCreationInfo.set_templateType(SP.ListTemplateType.genericList);  
  29.         clientContext.get_web().get_lists().add(newListCreationInfo);  
  30.         //Dispose the Catch Scope  
  31.         catchScope.dispose();  
  32.         //Instantiate the Finally Scope  
  33.         var finallyScope = exceptionScope.startFinally();  
  34.         //Update the newly created List  
  35.         var oList = clientContext.get_web().get_lists().getByTitle("ExceptionList");  
  36.         oList.set_description("Finally Updated Description");  
  37.         oList.update();  
  38.         //Dispose finallyScope  
  39.         finallyScope.dispose();  
  40.         // Dispose startScope  
  41.         startScope.dispose();  
  42.         //Execute the batch  
  43.         clientContext.executeQueryAsync(Success, Failure);  
  44.     }  
  45.   
  46.     function Success() {  
  47.         console.log("The list has been created successfully.");  
  48.     }  
  49.   
  50.     function Failure(sender, args) {  
  51.         console.log('Request failed - ' + args.get_message());  
  52.     }  
  53. </script>  
Output: Console output after implementing the exception handling mechanism is given below:

Output

Output

Summary: Thus, we have seen, how to implement an exception handling in JavaScript Object Model programming in SharePoint 2016 and Office 365. As a best practice, it is advised to add the exception handling blocks in JSOM code to take care of the unexpected road blocks during code execution.