Monday, April 16, 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:




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com