【发布时间】:2023-03-08 18:23:01
【问题描述】:
在你跑去谷歌之前,我已经阅读了很多关于异常处理的文章、帖子和 cmets,但我仍然停留在这些特定点上。
鉴于以下示例,您将如何处理以下场景?
- 如果 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());
}
}
【问题讨论】:
标签: exception exception-handling layer n-tier-architecture