tryCatch not catching error produced by install.packages within RStudio

后端 未结 3 1332
再見小時候
再見小時候 2021-01-22 02:02

Consider the following usage:

tryCatch(log(\"a\"), error = function(e) NULL)
#NULL

Now I\'m trying to do essentially the same, but in a more co

相关标签:
3条回答
  • 2021-01-22 02:53

    RStudio does not exectute the normal install.packages but instead does its own thing:

    look at the code in RStudio:

    > install.packages
    function (...) 
    .rs.callAs(name, hook, original, ...)
    <environment: 0x3e4b478>
    > .rs.callAs
    function (name, f, ...) 
    {
        withCallingHandlers(tryCatch(f(...), error = function(e) {
            cat("Error in ", name, " : ", e$message, "\n", sep = "")
        }), warning = function(w) {
            cat("Warning in ", name, " :\n  ", w$message, "\n", sep = "")
            invokeRestart("muffleWarning")
        })
    }
    <environment: 0x3bafa38>
    

    weird code, it recalls itself ... i was expecting a .Primitive() somewhere

    > sum
    function (..., na.rm = FALSE)  .Primitive("sum")
    

    but it is an ugly RStudio hack. if you look at install.packages in normal R you get:

    head(install.packages) # it is really long :P
    1 function (pkgs, lib, repos = getOption("repos"), contriburl = contrib.url(repos, 2 type), method, available = NULL, destdir = NULL, dependencies = NA,
    3 type = getOption("pkgType"), configure.args = getOption("configure.args"),
    4 configure.vars = getOption("configure.vars"), clean = FALSE,
    5 Ncpus = getOption("Ncpus", 1L), verbose = getOption("verbose"),
    6 libs_only = FALSE, INSTALL_opts, quiet = FALSE, keep_outputs = FALSE,
    ....

    0 讨论(0)
  • 2021-01-22 02:55

    Use the namespaced invocation:

    utils::install.packages()
    
    0 讨论(0)
  • 2021-01-22 03:02

    I'm going to suggest closing as off-topic because this is an RStudio problem. Basically, tryCatch is catching the error, but RStudio's error handler prints the error anyway. Thus the reason you're getting a return value:

    [[1]]
    NULL
    
    [[2]]
    NULL
    

    This means tryCatch works. RStudio just prints caught errors weirdly.

    0 讨论(0)
提交回复
热议问题