.Net HtmlTextWriter 的异常安全/处理?
我正在使用 .Net HtmlTextWriter
生成 HTML。
try
{
htw.RenderBeginTag( HtmlTextWriterTag.Span );
htw.Write(myObject.GenerateHtml());
htw.RenderEndTag( );
}
catch (Exception e)
{
GenerateHtmlErrorMessage(htw);
}
在此示例中,如果在 myObject.GenerateHtml()
期间触发错误异常,我将生成一个不错的错误 html,但其前面会出现一个开始 span
标记,即从未关闭。
我可以像这样重构它
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);
}
现在我的跨度不会打开,直到我完成了艰苦的工作,但这对我来说看起来很尴尬。 有没有办法用 HtmlWriter 进行回滚? 即使我不得不放入大量的 using 块。
我目前正在使用 .Net 2.0,但讨论 3.5 中的解决方案就可以了。
I am using a .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 error exception is fired during myObject.GenerateHtml()
, I will generate a nice error html but it will be preceded by an opening span
tag that is never closed.
I could refactor it like so
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 span doesn't open 'till I've done the hard work, but this just looks awkward to me. Is there any way do rollback with a HtmlWriter? Even if I had to put in loads of using blocks.
I'm currently working in .Net 2.0, but a discussion of solutions in 3.5 would be ok.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只关心在GenerateHtml()调用期间发生的错误,并且不喜欢第二种方法(这对我来说似乎很好),为什么不将结束跨度标记移动到finally块中,并拉出打开调用:
这样跨度始终打开并始终关闭。 如果GenerateHtml抛出异常,您可以捕获它并在关闭它之前在跨度内生成错误。
当然,如果尝试写入标签时发生异常,那么您无论如何都不会幸运地写入错误消息,因此我假设该问题正在其他地方处理。
If you are only concerned about errors that occur during the GenerateHtml() call, and don't like the second approach (which seems fine to me), why not move the closing span tag into a finally block, and pull out the open call:
This way the span is always opened and always closed. If GenerateHtml throws an exception, you catch it and generate the error inside the span, before closing it.
Of course, if the exception occurs trying to write the tags, then you are out of luck writing an error message anyway, so I'll assume that is being handled elsewhere.
您应该避免使用 try/catch,而是检查结果是否不是您所期望的。 我在这里唯一能看到的是 myHTML 可以为 null,所以尝试这样的操作:
string myHtml = myObject.GenerateHtml();
You should avoid using try/catch, and instead check if the result is not what you expected. The only thing I can see here, is that myHTML can be null, so try something like this:
string myHtml = myObject.GenerateHtml();