How to catch ‘Access Denied’ exception with try-catch in SharePoint

Problem:

Can’t catch ‘Access Denied” exception in try-catch block.

Case:

When the code tries to access an object that it has no permissions to access ‘access denied’ exception is thrown and by default it is handled by SharePoint by redirecting to ‘Access Denied’ page. That page doesn’t show much information for troubleshooting.
If you put the code that causes ‘access denied’ exception in try-catch block you will not be able to catch that exception because SharePoint has already handled it.

Solution:

To change this default behavior SPSecurity.CatchAccessDeniedException should be set to FALSE before your try-catch block.

bool originalState = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
	//your code that throws Access Denied exception
}
catch
{
	//get more info about the exception 
}
finally
{
	SPSecurity.CatchAccessDeniedException = originalState;
}
Advertisements

One Response to How to catch ‘Access Denied’ exception with try-catch in SharePoint

  1. Lawrence says:

    Thanks Naim! This helped a lot.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: