如何将警告和错误保存为函数的输出?

Aar*_*ica 39 error-handling r try-catch

我正在使用lapply大量项目上的复杂函数,我想保存每个项目的输出(如果有的话)以及生成的任何警告/错误,以便我可以告诉哪个项目产生了哪个警告/错误.

我找到了一种方法来捕捉警告withCallingHandlers(在此描述).但是,我也需要捕获错误.我可以将它包装在一个tryCatch(如下面的代码中),但是有更好的方法吗?

catchToList <- function(expr) {
  val <- NULL
  myWarnings <- NULL
  wHandler <- function(w) {
    myWarnings <<- c(myWarnings, w$message)
    invokeRestart("muffleWarning")
  }
  myError <- NULL
  eHandler <- function(e) {
    myError <<- e$message
    NULL
  }
  val <- tryCatch(withCallingHandlers(expr, warning = wHandler), error = eHandler)
  list(value = val, warnings = myWarnings, error=myError)
} 
Run Code Online (Sandbox Code Playgroud)

此函数的示例输出是:

> catchToList({warning("warning 1");warning("warning 2");1})
$value
[1] 1

$warnings
[1] "warning 1" "warning 2"

$error
NULL

> catchToList({warning("my warning");stop("my error")})
$value
NULL

$warnings
[1] "my warning"

$error
[1] "my error"
Run Code Online (Sandbox Code Playgroud)

关于SO的讨论tryCatch和错误处理有几个问题,但我发现没有解决这一特定问题的问题.请参阅如何检查函数调用是否会导致警告?,warnings()在函数内不起作用?如何解决这个问题?,以及如何告诉lapply忽略错误并处理列表中的下一件事?对于最相关的.

Mar*_*gan 45

也许这与你的解决方案相同,但我写了一个factory将普通旧函数转换为捕获它们的值,错误和警告的函数,所以我可以

test <- function(i)
    switch(i, "1"=stop("oops"), "2"={ warning("hmm"); i }, i)
res <- lapply(1:3, factory(test))
Run Code Online (Sandbox Code Playgroud)

结果的每个元素都包含值,错误和/或警告.这适用于用户功能,系统功能或匿名功能(factory(function(i) ...)).这是工厂

factory <- function(fun)
    function(...) {
        warn <- err <- NULL
        res <- withCallingHandlers(
            tryCatch(fun(...), error=function(e) {
                err <<- conditionMessage(e)
                NULL
            }), warning=function(w) {
                warn <<- append(warn, conditionMessage(w))
                invokeRestart("muffleWarning")
            })
        list(res, warn=warn, err=err)
    }
Run Code Online (Sandbox Code Playgroud)

和一些帮助处理结果列表

.has <- function(x, what)
    !sapply(lapply(x, "[[", what), is.null)
hasWarning <- function(x) .has(x, "warn")
hasError <- function(x) .has(x, "err")
isClean <- function(x) !(hasError(x) | hasWarning(x))
value <- function(x) sapply(x, "[[", 1)
cleanv <- function(x) sapply(x[isClean(x)], "[[", 1)
Run Code Online (Sandbox Code Playgroud)

  • 是的,同样的想法,但更好!你有没有考虑把它包装成一个包装?从我在这里看到的其他问题来看,其他人也觉得这也很有用. (3认同)

had*_*ley 16

试试评估包.

library(evaluate)
test <- function(i)
    switch(i, "1"=stop("oops"), "2"={ warning("hmm"); i }, i)

t1 <- evaluate("test(1)")
t2 <- evaluate("test(2)")
t3 <- evaluate("test(3)")
Run Code Online (Sandbox Code Playgroud)

它目前缺乏评估表达式的好方法 - 这主要是因为它的目标是在控制台上准确再现R输出的给定文本输入.

replay(t1)
replay(t2)
replay(t3)
Run Code Online (Sandbox Code Playgroud)

它还捕获消息,输出到控制台,并确保所有内容按照发生的顺序正确交错.


use*_*065 9

我已经合并了Martins soulution(/sf/answers/346703591/)和你得到的R-help邮件列表中的那个demo(error.catching).

主要思想是同时保留警告/错误消息以及触发此问题的命令.

myTryCatch <- function(expr) {
  warn <- err <- NULL
  value <- withCallingHandlers(
    tryCatch(expr, error=function(e) {
      err <<- e
      NULL
    }), warning=function(w) {
      warn <<- w
      invokeRestart("muffleWarning")
    })
  list(value=value, warning=warn, error=err)
}
Run Code Online (Sandbox Code Playgroud)

例子:

myTryCatch(log(1))
myTryCatch(log(-1))
myTryCatch(log("a"))
Run Code Online (Sandbox Code Playgroud)

输出:

> myTryCatch(log(1))

$ value [1] 0 $ warning NULL $ error NULL

> myTryCatch(log(-1))

$ value [1] NaN $警告$ error NULL

> myTryCatch(log("a"))

$ value NULL $ warning NULL $ error


rus*_*rce 6

我的回答(以及对Martin优秀代码的修改)的目的是使工厂编辑的函数返回预期的数据结构,如果一切顺利的话.如果遇到警告,则会将其附加到factory-warning属性下的结果中.data.table的setattr函数用于允许与该包兼容.如果遇到错误,结果是字符元素"工厂函数中发生错误",该factory-error属性将携带错误消息.

#' Catch errors and warnings and store them for subsequent evaluation
#'
#' Factory modified from a version written by Martin Morgan on Stack Overflow (see below).  
#' Factory generates a function which is appropriately wrapped by error handlers.  
#' If there are no errors and no warnings, the result is provided.  
#' If there are warnings but no errors, the result is provided with a warn attribute set.
#' If there are errors, the result retutrns is a list with the elements of warn and err.
#' This is a nice way to recover from a problems that may have occurred during loop evaluation or during cluster usage.
#' Check the references for additional related functions.
#' I have not included the other factory functions included in the original Stack Overflow answer because they did not play well with the return item as an S4 object.
#' @export
#' @param fun The function to be turned into a factory
#' @return The result of the function given to turn into a factory.  If this function was in error "An error as occurred" as a character element.  factory-error and factory-warning attributes may also be set as appropriate.
#' @references
#' \url{http://stackoverflow.com/questions/4948361/how-do-i-save-warnings-and-errors-as-output-from-a-function}
#' @author Martin Morgan; Modified by Russell S. Pierce
#' @examples 
#' f.log <- factory(log)
#' f.log("a")
#' f.as.numeric <- factory(as.numeric)
#' f.as.numeric(c("a","b",1))
factory <- function (fun) {
  errorOccurred <- FALSE
  library(data.table)
  function(...) {
    warn <- err <- NULL
    res <- withCallingHandlers(tryCatch(fun(...), error = function(e) {
      err <<- conditionMessage(e)
      errorOccurred <<- TRUE
      NULL
    }), warning = function(w) {
      warn <<- append(warn, conditionMessage(w))
      invokeRestart("muffleWarning")
    })
    if (errorOccurred) {
      res <- "An error occurred in the factory function"
    } 

    if (is.character(warn)) {
      data.table::setattr(res,"factory-warning",warn)
    } else {
      data.table::setattr(res,"factory-warning",NULL) 
    }

    if (is.character(err)) {
      data.table::setattr(res,"factory-error",err)
    } else {
      data.table::setattr(res, "factory-error", NULL)
    }  
    return(res)
  }
}
Run Code Online (Sandbox Code Playgroud)

因为我们没有将结果包装在一个额外的列表中,所以我们不能做出允许其某些访问器函数的假设,但是我们可以编写简单的检查并决定如何处理适合我们特定结果的案例.数据结构.

.has <- function(x, what) {
  !is.null(attr(x,what))
}
hasWarning <- function(x) .has(x, "factory-warning")
hasError <- function(x) .has(x, "factory-error")
isClean <- function(x) !(hasError(x) | hasWarning(x))
Run Code Online (Sandbox Code Playgroud)