Day to day good stuff I find regarding my work

Wednesday, April 11, 2007

Best Practise in error handling webparts in Sharepoint 2007

Uploaded as an article to CodeProject

When installing a webpart in Sharepoint 2007 you need to have some kind of model how to handle errors. This is the approach I have used.

The entry points in the code are

1. CreateChildControls
Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.

2. Render
Renders the control to the specified HTML writer.

The problem is that the user should get somekind of feedback in a readable format telling him OOhps the secound problem is how to communicate this to the System Administrator

My Approach

a) Create a private variable to store the Exception
private Exception childException = null;

b) In CreateChildControls have a try/catch and catch the error in the childException variable

catch (Exception exp)
HttpContext ctx = HttpContext.Current;
childException = ex;
c) In Render check if the have a try/catch and catch the error in the childException variable
and then display the result in the page by using labels..

protected override void Render(System.Web.UI.HtmlTextWriter writer)
if (childException != null)
displayErrorMsg(writer, childException);

catch (Exception ex)
displayErrorMsg(writer, ex);


private void displayErrorMsg(HtmlTextWriter writer, Exception ex)
this.Controls.Add(new LiteralControl(ex.Message));
if (ex.InnerException != null)
this.Controls.Add(new LiteralControl(ex.InnerException.Message));
this.Controls.Add(new LiteralControl());
HttpContext ctx = HttpContext.Current;

No comments: