【发布时间】:2014-04-17 12:15:09
【问题描述】:
Exception 类是否有唯一的 Id 或任何其他唯一的修饰符(GUID、...)?
我正在后端服务中记录生成的异常。但我的目标是只记录每个异常一次。
也许这里有一个有用的例子: 该服务有 3 层:
DAL (SQL-Interaction)
=> Exception A occurs here and is being logged into the database
BL (BusinessLayer)
=> Exception A is passed to here but isn't being logged
=> Exception B is thrown here and is being logged into the table
Services (Service Interface)
=> Exception A is passed to here but isn't being logged
=> Exception B is passed to here but isn't being logged
...
Client-solutions
我目前的解决方案(我个人非常不喜欢):
我编写了一个自己的异常(继承自基类异常)。当第一次抛出任何异常时,它会被记录下来。然后将其转换为我自己的例外并重新抛出。我自己的异常类型的异常没有记录在数据库中
示例(这是伪代码)
DAL - Layer
try{}
catch (Exception e)
{
// log in database
// log in logfile
// Cast to OwnException
// rethrown as OwnException
}
BL - Layer
try{}
catch (OwnException e)
{
// log in logfile
// rethrow e
}
catch (Exception e)
{
// log in database
// log in logfile
// Cast to OwnException
// rethrow as OwnException
}
更新:我真正在寻找的是一个 Id/unique 修饰符。我会扫描数据库中是否存在此 ID。如果这个 id 不存在,那么我会写一条记录。如果它存在,那么它只会被重新抛出。
【问题讨论】:
-
你为什么要在不同的地方多次登录?这有什么用?
-
如果 BL 层内发生异常,则需要记录它。如果它发生在 DAL 层内,那么我必须被记录。但是必须让客户端解决方案知道发生了异常。所以我向客户的方向重新抛出异常,这样他们就知道出了什么可怕的问题。我可以在顶层记录它,是的,但显然这里的最佳做法是登录每个方法。
标签: c# exception exception-handling