在你离开谷歌之前,我已经阅读了很多关于异常处理的文章、帖子和评论,但我仍然停留在这些具体问题上。
给出下面的示例,您将如何处理下列场景?
如果在DAL层中发生异常,并被包装在自定义异常中,则
如果我在DAL层中记录它,它将再次记录在全局处理程序中(使用elmah)。我可以让它恰如其分,但如果ServiceLayer需要将该异常转换为对用户更友好的消息或可能用于事务目的(想想回滚),会发生什么?我将丢失DAL异常中收集的信息(消息,不一定是堆栈跟踪)。
// UI
public static GetUser(int userId)
{
// Should I do validation here or in service layer
try
{
IUserService s = new UserService(userId);
s.GetUser(userId);
}
catch(ServiceLayerException ex)
{
// ex.Message displayed to user
}
}
// Service layer
public User GetUser(int userId)
{
try
{
return repo.GetUser(userId);
}
catch(DALException ex)
{
// user-friendly message displayed to user
throw new ServiceLayerException("User does not exist");
}
}
// DAL
public User GetUser(int userId)
{
try
{
// Query for user, if fails throw DALException
return userId;
}
catch (SqlException ex)
{
throw new DALException("Could not retrieve user with userId " + userId.ToString());
}
}
发布于 2012-03-29 19:29:37
就我个人而言,我更喜欢在煤层板上登录--在实际发生异常的地方,所以在第一种情况下,我会登录DAL。如果我们不想传递错误,或者允许elmah记录错误,那么Bal (服务层)可以处理错误(这并不是一件坏事,因为它将显示在错误页面并帮助跟踪异常)。服务层还可以将DAL错误作为内部异常传递,以便如果需要,可以在推进期间/之后访问DAL错误,并且可以根据需要在层间更改异常项。用户通常不会想要这样的信息,只会收到通常的哑巴消息。还可以使用事件来收集异常数据(带有专门的事件论证),并只返回布尔方法返回,这可以更可控和更可裁剪--尽管这样做会让您承担起是否传播的责任,而且很可能只用于“预期的”异常。
https://stackoverflow.com/questions/9931926
复制相似问题