Exclude security / handling with .Net HtmlTextWriter?

I am using .Net HtmlTextWriter

to generate HTML.

try
{
   htw.RenderBeginTag( HtmlTextWriterTag.Span );

   htw.Write(myObject.GenerateHtml());

   htw.RenderEndTag( );
}
catch (Exception e)
{
   GenerateHtmlErrorMessage(htw);
}

      

In this example, if an myObject.GenerateHtml()

error exception is thrown at time , I will generate a nice html error code, but it will be preceded by an opening tag span

that never closes.

I could reorganize it like this

try
{
   string myHtml = myObject.GenerateHtml();

   // now hope we don't get any more exceptions
   htw.RenderBeginTag( HtmlTextWriterTag.Span );
   htw.Write(myHtml)     
   htw.RenderEndTag( );
}
catch (Exception e)
{
   GenerateHtmlErrorMessage(htw);
}

      

Now my flight won't open until I have done the hard work, but I just feel uncomfortable. Is there a way to rollback using HtmlWriter? Even if I had to load heaps of blocks.

I'm currently working in .Net 2.0, but a discussion of solutions in 3.5 would be fine.

0


source to share


2 answers


If you are only concerned about the errors that occur during the call to GenerateHtml () and I don't like the second approach (which I think is fine), why not move the closing span tag into the finally block and pull out the open call:

htw.RenderBeginTag( HtmlTextWriterTag.Span );
try
{
   htw.Write(myObject.GenerateHtml());
}
catch (Exception e)
{
   GenerateHtmlErrorMessage(htw);
}
finally
{
   htw.RenderEndTag( );
}

      



Thus, the range is always open and always closed. If GenerateHtml throws an exception, you break it and generate an error inside the range before closing it.

Of course, if an exception is thrown while trying to write the tags, you still fail to write an error message, so I assume this is handled elsewhere.

+1


source


You should avoid using try / catch and instead check if the result is not what you expected. The only thing I see here is that myHTML can be null, so try something like this:

string myHtml = myObject.GenerateHtml ();



if (myHTML != null)
{
   htw.RenderBeginTag( HtmlTextWriterTag.Span );
   htw.Write(myHtml)     
   htw.RenderEndTag( );
else
{
   GenerateHtmlErrorMessage(htw);
}

      

-2


source







All Articles