CodeGo.net>如何实现解析异常处理?
作者:互联网
我正在创建一个解析应用程序,该应用程序解析约20个站点,每个站点约7-15个值.伪代码如下所示:
ParserA : ParserBase
{
public override SomeEntity Parse(...)
{
SomeEntity se = new SomeEntity();
//some code, parsing value1;
//some code, parsing value1;
//some code, parsing value1;
//some code, parsing value2;
//some code, parsing value2;
//some code, parsing value2;
//some code, parsing value3;
//some code, parsing value3;
//some code, parsing value3;
//some code, parsing value4;
//some code, parsing value4;
//some code, parsing value4;
...
return se;
}
}
ParserB : ParserBase {...}
ParserC : ParserBase {...}
...
等等
一旦解析器无法很好地处理html(布局就会发生
随时间变化),我需要实现exceptionHandling和
记录.我需要尽可能地解析,并且必须记录错误.我知道两种处理方法:
public override SomeEntity Parse(...)
{
SomeEntity se = new SomeEntity();
try {
//some code, parsing value1;
//some code, parsing value1;
//some code, parsing value1;
//some code, parsing value2;
//some code, parsing value2;
//some code, parsing value2;
//some code, parsing value3;
//some code, parsing value3;
//some code, parsing value3;
//some code, parsing value4;
//some code, parsing value4;
//some code, parsing value4;
...
}
catch (Exception e)
{
//Log
}
return se;
}
优点:易于实施
缺点:如果我在value5处获得ex,则我没有机会解析value6,7等.
2)
ParserA : ParserBase
{
public override SomeEntity Parse(...)
{
try
{
//some code, parsing value1;
//some code, parsing value1;
//some code, parsing value1;
}
catch(Exception e)
{
// Log
}
try
{
//some code, parsing value2;
//some code, parsing value2;
//some code, parsing value2;
catch(Exception e)
{
// Log
}
try
{
//some code, parsing value3;
//some code, parsing value3;
//some code, parsing value3;
catch(Exception e)
{
// Log
}
try
{
//some code, parsing value4;
//some code, parsing value4;
//some code, parsing value4;
catch(Exception e)
{
// Log
}
...
}
}
优点:可以解析的所有内容都被解析;
缺点:复制粘贴过多(记住20个解析器,每个解析器7-15个值.
我想写更少,做更多,所以我实现了Safecall函数,该函数接受委托并在try-catch块中执行它,并记录ot.所以现在我要写这个:
SafeCall( () => {
//some code, parsing value4;
//some code, parsing value4;
//some code, parsing value4;
});
代替这个:
try
{
//some code, parsing value4;
//some code, parsing value4;
//some code, parsing value4;
catch(Exception e)
{
// Log
}
这是一个好的解决方案,还是我正在重新发明方形齿轮?
解决方法:
可以使用SafeCall选项,它易于使用,易于阅读,如果您想更改日志记录机制,则可以随时更改SafeCall实现.
标签:logging,error-handling,c,design-patterns 来源: https://codeday.me/bug/20191209/2096684.html