Skip to content

How to catch Access Denied errors with try-catch block in SharePoint

May 16, 2011

When you create a web part that uses the SharePoint object model to read some data from SharePoint lists you must be prepared to situations when the actual user does not have Read permission on the list and the call raises an Access Denied error. In this case by default the SharePoint framework redirects the user to the standard error page (_layouts/AccessDenied.aspx).

Usually it is nicer to handle the Access Denied error inside the web part and provide the user with a more friendly error message right on the page he is working on. To do this, we need to catch the Access Denied exception with a try catch block. Sounds simple but after the first attempt we will see that the exception is not caught and the error page still comes up.

The solution is to set the SPSecurity.CatchAccessDeniedException flag to false:

bool originalCatchValue = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;

   // access denied comes here
catch (UnauthorizedAccessException ex)
   // handle exception
   // reset the flag
   SPSecurity.CatchAccessDeniedException = originalCatchValue;

  1. Excellent! Thanks, this helped a lot.

  2. Thanks!

  3. Nate permalink

    Same here, exactly what I needed! Thanks!

  4. Michael Geary permalink

    Exactly what I was looking for. THANKS!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: