6

I need to handle unauthorized exception.. My code is something like:

try { //MY CODE } catch (Exception exx) { //My Code } 

I can't understand why if a NOT AUTH exception is thrown, my code didn't pass inside the Exception... UnauthorizedAccessException extends Exception, so WHY this code wont' work?

Thank you very much!

2 Answers 2

12

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; } 
1
  • It is recommended to wrap with SPSecurity.RunWithElevatedPrivileges(delegate(){//The code above}) Commented Aug 16, 2020 at 18:25
2

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.