gpt4 book ai didi

c# - 如何在解析中实现异常处理?

转载 作者:行者123 更新时间:2023-11-30 16:32:51 25 4
gpt4 key购买 nike

我正在创建一个解析应用程序,它解析大约 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(布局就会发生随时间变化),我需要实现异常处理和记录。我需要尽可能多地解析,并且必须记录错误。我知道 2 种处理方法:

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 处获得 exc,我就没有机会解析 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 函数,它接受委托(delegate)并在 try-catch block 中执行它,并记录 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 实现。

关于c# - 如何在解析中实现异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3708331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com