Friday, July 20, 2012

Exception handling in client object model

We are familiar with try, catch and finally. It has been around for many years. We cannot ignore that at all as it plays a vital role in development.

Same is the case when we write a client object model code for SharePoint 2010.

ExceptionHandlingScope is a new class that has been introduced in SharePoint 2010 which allows us to perform the same action.

Let’s say you are working with managed client object model.

Here is a way to get a context of ExceptionHandlingScope and to work with it.
ClientContext ccontext = new ClientContext("site collection path");           
ExceptionHandlingScope exceptionscope = new ExceptionHandlingScope(ccontext);           
using (exceptionscope.StartScope())
            {
                using (exceptionscope.StartTry())
                {
                               // Code Block
                }
 
                using (exceptionscope.StartCatch())
                {                    
                     //Code Block which handles the exception
                }
 
                using (exceptionscope.StartFinally())
                {                    
                    //Code Block that always executes
                }
            }
Let’s say you are working in ECMA client object model and would like to handle exception

function Example()
{
this.clientcontext = new SP.ClientContext.get_current();
var clientScope = new SP.ExceptionHandlingScope(this.clientcontext);
var startScope = clientScope.startScope();
var tryScope = clientScope.startTry();
// Code Block
tryScope.dispose();
var catchScope = clientScope.startCatch();
 //Code Block which handles the exception
catchScope.dispose();
var finallyScope = clientScope.startFinally();
//Code Block that always executes
finallyScope.dispose();
startScope.dispose();

}
I hope this will help developing smoother and robust client object model application.

No comments:

Post a Comment