Quick Tip: Throwing SPExceptions

Just a quick note for developers. If you want normal code execution to be terminated and want a useful message to be presented back to the end user on the SharePoint error page, throw an exception that either is of type SPException, or derives from type SPException. If this is done, the associated exception message will be presented to the end-user (see screenshot). If, however, the exception thrown does not derive from SPException, a less friendly error message will be shown - "An unexpected error has occurred".

image

Example code

if (someCondition)

{

    throw new SPException("<Your custom message here>");

}

Note that in either case, if you do not catch the exception and CustomErrors is set to on in the web.config, the exception will be passed to the unified logging service (ULS) and provided logging is set to verbose (set through Central Admin->Operation->Diagnostic Logging), the message will be added to the trace logs (typically residing at 12\Logs).

Also remember to exclude any sensitive information when throwing the exception (e.g. database connection details, credentials, personal information etc).

 

Rob Nowik

Developer Consultant

Microsoft Consulting Services UK

Click here to read my bio