File: tryWithWarnings.R

package info (click to toggle)
r-cran-lavasearch2 2.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,832 kB
  • sloc: cpp: 28; sh: 13; makefile: 2
file content (65 lines) | stat: -rw-r--r-- 1,984 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
### tryWithWarnings.R --- 
#----------------------------------------------------------------------
## author: Brice Ozenne
## created: aug 29 2017 (09:52) 
## Version: 
## last-updated: feb  5 2018 (16:07) 
##           By: Brice Ozenne
##     Update #: 20
#----------------------------------------------------------------------
## 
### Commentary: 
## 
### Change Log:
#----------------------------------------------------------------------
## 
### Code:


##' @title Run an Expression and Catch Warnings and Errors
##' @description Similar to \code{try} but also returns warnings.
##' 
##' @param expr the line of code to be evaluated
##' @details
##' from https://stackoverflow.com/questions/4948361/how-do-i-save-warnings-and-errors-as-output-from-a-function
##' 
##' @return A list containing:
##' \itemize{
##' \item value the result of the evaluation of the expression
##' \item warnings warning(s) generated during the evaluation of the expression
##' \item error error generated during the evaluation of the expression
##' }
##'
##' @examples
##' FctTest <- function(x){
##'   return(log(x))
##' }
##' tryWithWarnings(FctTest(-1))
##' tryWithWarnings(FctTest(1))
##' tryWithWarnings(FctTest(xxxx))
##'
##' @export
tryWithWarnings <- function(expr) {
    myWarnings <- NULL
    myError <- NULL
    FCT.envir <- environment()
    wHandler <- function(w) {
        assign("myWarnings", value = c(myWarnings, list(w)), envir = FCT.envir)
        invokeRestart("muffleWarning")
    }
    eHandler <- function(e) {
        assign("myError", value = e, envir = FCT.envir)
        return(NULL)
    }
    val <- withCallingHandlers(tryCatch(expr, error = eHandler), warning = wHandler)
    
    out <- list(value = val,
                warnings = myWarnings,
                error = myError)
    
  return(out)
}


#----------------------------------------------------------------------
### tryWithWarnings.R ends here