在tryCatch中警告之前处理错误

时间:2013-10-17 17:56:01

标签: r exception-handling try-catch

我正在处理一个抛出错误和警告的函数。 (相关:A Warning About Warning

通常,警告会发生错误。在这些情况下,我想忽略警告并仅处理错误。

另一方面,如果只有一个警告(没有错误),那么我想抓住警告。

我正在尝试使用臭名昭着的易用tryCatch

我的直接问题是: 有没有办法强制tryCatcherror之前处理warning(或在出现错误时忽略警告)?

我对?tryCatch文档的理解是条件处理FIFO,在这种情况下,我的直接问题的答案是否 - 至少不是直接的。在这种情况下,是否可以处理警告,然后在仍然捕获错误的同时继续执行此功能?

我无法使用的解决方案:

  • suppressWarnings#我还想抓住并处理警告
  • options(warn=2)#某些警告无害
     relevant from `?tryCatch`
     

如果在评估expr时发出条件信号,则检查已建立的处理程序,从最近建立的处理程序开始,匹配条件的类。当在一个tryCatch中提供多个处理程序时,第一个被认为比第二个更新。如果找到一个处理程序,则控制转移到建立处理程序的tryCatch调用,找到处理程序并解除所有更新的处理程序,以条件作为其参数调用处理程序,并且处理程序返回的结果返回为tryCatch调用的值。

以下是玩具示例:

F.errorAndWarning <- function() {
    warning("Warning before the error")
    cat("I have moved on.")
    stop("error")
    TRUE
}
F.error <- function() {stop("error"); TRUE}


test <- function(F)
  tryCatch(expr= {F}()
          , error=function(e)   cat("ERROR CAUGHT")
          , warning=function(w) cat("WARNING CAUGHT")
          )

test(F.error)
# ERROR CAUGHT
test(F.errorAndWarning)
# WARNING CAUGHT

预期/理想输出:

test(F.errorAndWarning)
# ERROR CAUGHT

4 个答案:

答案 0 :(得分:9)

这与有关,是否可以处理警告,然后在仍然捕获错误的同时继续执行此功能?“问题。

我遇到了类似的问题,我希望将警告和错误的日志记录功能绑定到try catch,并在警告后始终继续,并且还能够在try catch中执行多次尝试,例如:用于访问脆弱的网络驱动器。这就是我最终使用的。这个或更简化的版本可以帮助您完成后续工作。

MyLibrary.Sys.Try <- function(
    expr,                   # Expression that will be evaluated by the call to Try
    errorMessage="",        # Optional prepended string to add to error output
    warningMessage="",      # Optional prepended string to add to warning output
    failureMessage="",      # Optional prepended string to add to failing all attempts
    finally=NULL,           # Optional expression to be executed at the end of tryCatch
    attempts=1,             # Number of attempts to try evaluating the expression
    suppressError=TRUE,     # Should the call just log the error or raise it if all attempts fail
    quiet=FALSE             # Return expression normally or as invisible
) {
    tryNumber <- 0
    while(tryNumber<attempts) {
        tryNumber <- tryNumber + 1

        # If not suppressing the error and this is the last
        # attempt then just evaluate the expression straight out
        if(tryNumber == attempts && !suppressError){
            # NOTE: I think some warnings might be lost here when
            # running in non-interactive mode. But I think it should be okay
            # because even nested dispatch seems to pick them up:
            # MyLibrary.Sys.Try(MyLibrary.Sys.Try(function(),suppressError=F))
            return(expr)
        }

        tryCatch({
            # Set the warning handler to an empty function
            # so it won't be raised by tryCatch but will
            # be executed by withCallingHandlers
            options(warning.expression=quote(function(){}))
            withCallingHandlers({
                if(quiet) {
                    return(invisible(expr))
                } else {
                    return(expr)
                }
            },error=function(ex){
                MyLibrary.Sys.Log.Error(errorMessage,ex)
            }, warning=function(warn){
                # Had issues with identical warning messages being
                # issued here so to avoid that only log it the first
                # time it happens in a given minute. 
                warnStamp <- paste(Sys.time(),warn,collapse="_",sep="")
                if(!identical(warnStamp,getOption("MyLibrary.LAST.WARNING"))) {
                    if(!(interactive() && is.null(getOption("warning.expression")))){
                        MyLibrary.Sys.Log.Warning(warningMessage,warn)
                    }
                    options(MyLibrary.LAST.WARNING=warnStamp)
                }
            })
        },error=function(ex){
            # Suppressing the error since it's been logged
            # by the handler above. Needs to be suppressed
            # to not invoke the stop directly since the
            # handler above passes it through.
        },finally={
            # Set the warning handler to the default value
            # of NULL which will cause it to revert to it's
            # normal behaviour. If a custom handler is normally
            # attached it would make sense to store it above
            # and then restore it here. But don't need that now
            options(warning.expression=NULL)
            if(!is.null(finally)){
                if(quiet) {
                    return(invisible(finally))
                } else {
                    return(finally)
                }
            }
        })
    }

    msg <- paste(ifelse(nchar(failureMessage)>0," - ",""),"Failed to call expression after ",attempts," attempt(s)",sep="")
    MyLibrary.Sys.Log.Error(failureMessage,msg)
}

答案 1 :(得分:5)

我会写一个执行expression的函数并优先处理错误。

prioritize.errors <- local({
    # this function executes an expression and stores the warnings 
    # until it finishes executing.
    warnings <- list()
    w.handler <- function(w) {
        warnings <<- c(warnings, list(w))
        invokeRestart('muffleWarning') # here's the trick
    }
    function(expr) {
        withCallingHandlers({expr}, warning=w.handler)
        for (w in warnings) warning(w)
        warnings <<- list()
    }
})

F.warning <- function() {
    warning("a warning")
    message('ok')
}


test <- function(expr) {
    tryCatch(expr, 
        error=function(e) cat("ERROR CAUGHT"), 
        warning=function(w) cat("WARNING CAUGHT")
    )
}

test(prioritize.errors(F.error()))
# ERROR CAUGHT 

test(prioritize.errors(F.warning()))
# ok
# WARNING CAUGHT

test(prioritize.errors(F.errorAndWarning()))
# I have moved on.ERROR CAUGHT

答案 2 :(得分:4)

我在pander包中编写了一个方便的帮助函数,用于捕获标准输出上打印的所有警告,错误和任何内容,以及调用中返回的原始R对象:

> library(pander)
> evals('F.errorAndWarning()')
[[1]]
$src
[1] "F.errorAndWarning()"

$result
NULL

$output
NULL

$type
[1] "error"

$msg
$msg$messages
NULL

$msg$warnings
[1] "Warning before the error"

$msg$errors
[1] "error"


$stdout
[1] "I have moved on."

attr(,"class")
[1] "evals"

答案 3 :(得分:2)

这三个答案都非常广泛而出色,但是我认为很多人也在寻找一种简短,简单的方式来处理警告,但仍在继续执行。如Matthew所示,可以很快完成:通过调用重新启动(并使用withCallingHandlers):

test <- function(FUN) withCallingHandlers(
  expr=FUN(),
  error=function(e) cat("ERROR CAUGHT\n"),
  warning=function(w) {cat('WARNING CAUGHT\n'); invokeRestart(findRestart('muffleWarning'))}
)

这仍然会打印警告(即使以后会产生错误),但继续执行