Wednesday, May 4, 2011

How to do exception handling in client object model in SharePoint 2010

In this post we will discuss how to do exception handling in client object model in SharePoint 2010?

Also you can check out:

- How to Create List and Add Item to that List using SharePoint 2010 client object model?

- Implement a breadcrumb into SharePoint 2010 website

- Change column name of list using SharePoint 2013 client object model in autohosted apps

Managed Object Model, Silverlight client object model, JavaScript client object model provide a mechanism for sending error-handling instructions to the server along with the batch operations. The ExceptionHandlingScope object allows you to define a try-catch-finally block that embodies server-side operations. If errors occur during processing on the server, they are handled on the server by the code embodied in ExceptionHandlingScope.

using (ClientContext context = new ClientContext("URL of the site"))
//Set up error handling
ExceptionHandlingScope exceptionScope = new ExceptionHandlingScope(context);
using (exceptionScope.StartScope)
using (exceptionScope.StartTry)
//Anything you want to do
using (exceptionScope.StartCatch)
//Fails If any exception occured and you can write code to handle the exception
using (exceptionScope.StartFinally)
//Try to do anything you want to do in the finally block
//Execute the entire try-catch as a batch!

Here the ExecuteQuery method is called only once, and it will send all the operations defined in the exception handling scope to the server in a single batch.

Also ExceptionHandlingScope class provides different properties like ServerErrorCode, ServerErrorValue, and ServerStackTrace which can be used to analyze the server error and decide about what to do.

No comments:

Post a Comment