gpt4 book ai didi

r - 如何在tryCatch中显示错误位置?

转载 作者:行者123 更新时间:2023-12-02 00:26:11 27 4
gpt4 key购买 nike

在使用 tryCatch 处理异常时,使用 options(show.error.locations = TRUE) 显示错误位置似乎不起作用。我正在尝试显示错误的位置,但我不知道如何:

options(show.error.locations = TRUE)

tryCatch({
some_function(...)
}, error = function (e, f, g) {
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
})

如果我然后查看变量e,该位置似乎不存在:

> str(e)
List of 2
$ message: chr "missing value where TRUE/FALSE needed"
$ call : language if (index_smooth == "INDEX") { rescale <- 100/meanMSI[plotbaseyear] ...
- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"

如果我不捕获错误,它将与源文件和行号一起打印在控制台上。如何用tryCatch来做呢?

最佳答案

上下文

正如 Willem vanDoesburg 所指出的,不可能使用 traceback() function使用 tryCatch() 显示错误发生的位置,据我所知,目前没有实用的方法可以在使用 tryCatch 时使用 R 中的基本函数存储错误的位置.

单独的错误处理程序的想法

我找到的可能的解决方案由两部分组成,主要的部分是编写一个类似于 Chrispy from "printing stack trace and continuing after error occurs in R" 的错误处理程序它会生成一个包含错误位置的日志。第二部分是将输出捕获到变量中,类似于 Ben Bolker in "is it possible to redirect console output to a variable" 的建议。 .

当错误发生并处理时,R 中的调用堆栈似乎会被清除(我可能是错的,因此欢迎任何信息),因此我们需要在错误发生时捕获错误。

脚本有错误

我使用了您之前关于 where 和 R error occured 的问题之一中的示例。将以下函数存储在名为“TestError.R”的文件中,我在下面的示例中调用该文件:

# TestError.R
f2 <- function(x)
{
if (is.null(x)) "x is Null"
if (x==1) "foo"
}

f <- function(x)
{
f2(x)
}


# The following line will raise an error if executed
f(NULL)

错误追踪功能

这是我根据上面提到的 Chrispy 代码改编的函数。执行时,如果出现错误,下面的代码将打印错误发生的位置,在上述函数的情况下,它将打印:“发生错误:Test.R#9:f2(x)”“发生错误:Test.R#14:f(NULL)” 表示错误结果来自第 14 行的 f(NULL) 函数存在问题,该函数引用了第 9 行的 f2() 函数

# Error tracing function
withErrorTracing = function(expr, silentSuccess=FALSE) {
hasFailed = FALSE
messages = list()
warnings = list()

errorTracer = function(obj) {

# Storing the call stack
calls = sys.calls()
calls = calls[1:length(calls)-1]
# Keeping the calls only
trace = limitedLabels(c(calls, attr(obj, "calls")))

# Printing the 2nd and 3rd traces that contain the line where the error occured
# This is the part you might want to edit to suit your needs
print(paste0("Error occuring: ", trace[length(trace):1][2:3]))

# Muffle any redundant output of the same message
optionalRestart = function(r) { res = findRestart(r); if (!is.null(res)) invokeRestart(res) }
optionalRestart("muffleMessage")
optionalRestart("muffleWarning")
}

vexpr = withCallingHandlers(withVisible(expr), error=errorTracer)
if (silentSuccess && !hasFailed) {
cat(paste(warnings, collapse=""))
}
if (vexpr$visible) vexpr$value else invisible(vexpr$value)
}

存储错误位置和消息

我们调用上面的脚本TestError.R,并将打印输出捕获到一个变量中,这里称为errorStorage,我们可以稍后处理或简单地显示。

errorStorage <- capture.output(tryCatch({
withErrorTracing({source("TestError.R")})
}, error = function(e){
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
}))

因此,我们将 e 的值与调用和消息以及错误位置的位置一起保存。errorStorage 输出应如下所示:

[1] "[1] \"Error occuring: Test.R#9: f2(x)\"    \"Error occuring: Test.R#14: f(NULL)\""
[2] "ERROR: argument is of length zero "
[3] "in if (x == 1) \"foo\""

希望这可能有所帮助。

关于r - 如何在tryCatch中显示错误位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40629715/

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