Sharepoint - How to Handle Unathorized Exception
SharePoint “handles” Access denied exceptions by catching the exception internally and then redirecting the user to a landing page where they can log in to the site. By default this is generally “_layouts/AccessDenied.aspx”.
Since SharePoint redirects the request to the default Access Denied landing page you cannot catch the UnAuthorizedAccessException as the redirect causes a ThreadAbortException to be thrown so your code will never get executed.
In order to handle a thrown UnAuthorizedAccessException
within your code you first need to set the property CatchAccessDeniedException
(part of the SPSecurity class) to false. Doing so means that the Access exceptions aren’t handled by the SharePoint platform and the request isn’t redirected.
bool orgcatchvalue = SPSecurity.CatchAccessDeniedException;
try{
SPSecurity.CatchAccessDeniedException = false;
//your code that may throw an authorization exception
}
catch(UnAuthorizedAccessException)
{
//Code to handle exception
}
finally
{
//set the value back to what it was
SPSecurity.CatchAccessDeniedException = orgcatchval;
}
You can also wrap your code in a using statement like this
using (new SPSecurity.SuppressAccessDeniedRedirectInScope())
{
try
{
// Code here
}
catch (UnauthorizedAccessException ex)
{
// code here
}
}
Doing so will ensure that the SPSecurity.CatchAccessDeniedException boolean is always set back to its previous state and avoid security leaks.