Handling errors before warnings in tryCatch

后端 未结 4 866
萌比男神i
萌比男神i 2020-12-03 18:24

I am dealing with a function that is throwing both errors and warnings. (related: A Warning About Warning )

Often, a warning will proceed an error. In thes

4条回答
  •  醉话见心
    2020-12-03 18:30

    I would write a function that executes an expression and prioritizes the errors.

    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
    

提交回复
热议问题