Answer to question about error handling with lapply始终返回public class ProtocolsLayer : Layer
{
private IFrameworkDependencyResolver _resolver;
private IConfigurationService _configService;
public ProtocolsLayer(IFrameworkDependencyResolver resolver, IConfigurationService configurationService)
{
_resolver = resolver;
_configService = configurationService;
}
void HandleConnection1()
{
// What I have at the moment (terrible):
// Resolve the fitting services (All keyed - key is received by the type, Resolve and ResolveWithParameters used here are my wrappers)
var agent = _resolver.Resolve<IFramingAgent>(typeof(Protocol1FramingAgent));
var algo = _resolver.Resolve<IFramingAlgorithm>(typeof(Protocol1FramingAlgorith));
var parser = _resolver.Resolve<IFramingParser>(typeof(Protocol1FramingParser));
// A parameter I get and pass to each protocol at runtime
var protocolConfig = _configService.GetConfig<Protocol1Configuration>();
// Finally resolve the protocol with it's parameters:
protocol = _resolver.ResolveWithParameters<IProtocol>(typeof(Protocol1), new List<object>{
agent, resolver, parser, protocolConfig
});
//...
// Theres gotta be a better way!!
}
void HandleConntection2()
{
// Same as in protocol1
}
void HandleConnection3()
{
// Same as in protocol1
}
}
或NA
,即
NULL
但是,这不够通用,因为myfun <- function(s) {
tryCatch(doSomething(s), error = function(e) { return(NULL) }
}
可能会返回doSomething(s)
或NULL
本身。因此,理想情况下我希望NA
编写,以便在myfun
之后,我可以以某种方式获取失败元素的所有索引。怎么做?
答案 0 :(得分:2)
通过使用identity()
res = lapply(list(1, "two", 3), function(i) tryCatch({
sqrt(i)
}, error=identity)
检查错误
vapply(res, is, logical(1), "error")
返回错误条件通常会更好地返回“{magic”值,例如NA
或NULL
,除非下游分析与返回的值无缝协作。
作为更高级的解决方案,创建更复杂的条件或扩展错误类
my_condition = function(err)
structure(list(message=conditionMessage(err),
original=err), class=c("my", "condition"))
并返回
res <- lapply(list(1, "two", 3), function(i) {
tryCatch({
sqrt(i)
}, error=my_condition)
})