gpt4 book ai didi

c# - SingleOrDefault 异常处理

转载 作者:行者123 更新时间:2023-11-30 15:29:28 25 4
gpt4 key购买 nike

我有一个调用 SingleOrDefault 方法 3 次并在任何序列具有多个匹配元素时记录异常的代码。

如果我想检查这段代码的哪一部分抛出异常,问题就开始了。

是否可以从此异常中获取一些有用的信息,如谓词参数或集合类型以进行更详细的跟踪?

像这样 - 序列包含多个匹配元素。集合 IEnumrable|ParamType| param {Predicate param toString()}

 public void GetSingleOrDefaultTest(){

try{

var user = Users.SingleOrDefault(e => e.Id == 1);

var profile = UserProfiles.SingleOrDefault(e => e.Id == 1);

var profile2 = UserProfiles.SingleOrDefault(e => e.Id == 2);


} catch(InvalidOperationException ex){
Log(ex);
}

}

最佳答案

如果您想知道哪个语句发出错误,您必须单独检查它们。在每次 SingleOrDefault 调用时捕获 InvalidOperationException 并将其包装在一个新的异常中,您可以在其中填充其他信息。

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);
}

编辑:

您还可以通过以下方式封装单个 try catch

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: Sequence contains more than one matching element (Collection: IEnumerable`1[User], param: e => e.Id == 1)

关于c# - SingleOrDefault 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23674792/

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