New to SharePoint 2010 is the ability for developers to readily log to either the SharePoint Unified Logging Service (ULS) or to the Windows application event log. What a win-win-win situation for all involved, from the developer to the end user to the admin. The namespace to investigate if you're interested in performing either of these tasks is Microsoft.SharePoint.Administration. More specifically, the classes under the prefix SPDiagnostics (SPDiagnosticsArea, SPDiagnosticsCategory, ...). Even more specifically, the methods SPDiagnosticsService.WriteTrace (for ULS logging) and SPDiagnosticsService.WriteEvent (for Windows application event logging).
A great place to put this type of logging is in web parts. Always be sure to wrap your CreateChildControls or Render methods with a try/catch. There's nothing worse than the whole page blowing up just because one piece of the page has failed unexpectedly. On to the example....
catch (
Exception ex)
{
SPDiagnosticsService diagService =
SPDiagnosticsService.Local;
SPDiagnosticsCategory diagCategory = diagService.Areas[
"SharePoint Foundation"].Categories[
"Web Parts"];
string exceptionId =
"Web Part Exception Unique ID: " +
Guid.NewGuid().ToString();
string exceptionMsg = exceptionId +
" " + ex.Message + ex.StackTrace;
diagService.WriteTrace(0, diagCategory,
TraceSeverity.Unexpected, exceptionMsg);
(...)
}
At this point, it'd be good to write something back to the user of your web part. Depending on the method you're overriding, you would replace the above ellipsis with code to either add some literal controls to the web part controls collection, or by writing directly to the HTMLTextWriter provided.
writer.WriteLine(
"An unexpected error has occurred.");
writer.WriteBreak();
writer.WriteLine(
"If this problem persists, please contact your administrator.");
writer.WriteBreak();
writer.WriteBreak();
writer.WriteLine(
"Events have been added to the ULS log.");
writer.WriteBreak();
writer.WriteLine(exceptionId);
Also new to SharePoint 2010 is a more useful error messaging system in general. If a page errors out, a dialog box containing a correlation ID is made available for admins to use in troubleshooting. You may be asking yourself, how do I include this correlation ID into my message back to the user.
I did a lot of digging and found
this post by Tobias Zimmergren. In the section titled "Get the current Correlation ID by using code", he talks about just how to do this. However, in my opinion, this is overkill. I say this because...
1. The correlation ID is not unique to the error itself. It really reflects the page request as a whole. Therefore several lines, at least in the ULS log, will have this correlation ID stuck on the end of them.
and
2. You're already providing the system administrator a new GUID that uniquely identifies this error.