如果您想知道哪个语句导致了错误,您必须单独检查它们。抓住InvalidOperationException
在每一个SingleOrDefault
调用并将其包装在一个新的异常中,您可以在其中填充附加信息。
try
{
User user;
UserProfile profile;
UserProfile profile2;
try
{
user = Users.SingleOrDefault(e => e.Id == 1);
}
catch (InvalidOperationException ex)
{
throw new InvalidOperationException("User lookup for Id = 1 failed", ex);
}
try
{
profile = UserProfiles.SingleOrDefault(e => e.Id == 1);
}
catch (InvalidOperationException ex)
{
throw new InvalidOperationException("User profile lookup for Id = 1 failed", ex);
}
try
{
profile2 = UserProfiles.SingleOrDefault(e => e.Id == 2);
}
catch (InvalidOperationException ex)
{
throw new InvalidOperationException("User profile lookup for Id = 2 failed", ex);
}
// work with user, profile and profile2
}
catch(InvalidOperationException ex)
{
Log(ex);
}
Edit:
您还可以通过以下方式封装单个尝试捕获
private static T GetSingleOrDefault<T>(IEnumerable<T> collection, Expression<Func<T, bool>> predicate)
{
try
{
return collection.SingleOrDefault(predicate.Compile());
}
catch (InvalidOperationException e)
{
var message = string.Format(
"{0} (Collection: {1}, param: {2})",
e.Message,
collection.GetType(),
predicate);
throw new InvalidOperationException(message);
}
}
这样你的代码看起来就像
try
{
var user = GetSingleOrDefault(Users, e => e.Id == 1);
var profile = GetSingleOrDefault(UserProfiles, e => e.Id == 1);
var profile2 = GetSingleOrDefault(UserProfiles, e => e.Id == 2);
// work with user, profile and profile2
}
catch(InvalidOperationException ex)
{
Log(ex);
}
这会产生类似这样的消息
System.InvalidOperationException:序列包含多个匹配元素(集合:IEnumerable`1[User],参数:e => e.Id == 1)