0

I found this very helpful factory to convert any function into a function that capture its values, errors, and warnings (How do I save warnings and errors as output from a function?):

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)
}

My problem is that errors/warnings are also shown on screen (on top of being captured by the factory). How can I change it so that errors/warnings do not show on screen? Thanks

Community
  • 1
  • 1
kalka
  • 3
  • 4
  • Can you clarify what you mean? `f = factory(stop("oops")); res = f()` returns without any output to the screen. – Martin Morgan Feb 25 '16 at 18:45
  • You are right Martin... I was not clear. The function I am using with factory downloads streaming data from a financial website. It outputs several messages to screen via cat. Some of these messages end up being errors and can block the function. The function has a verbose parameter which can block all cat messages. – kalka Feb 26 '16 at 08:19
  • If I set verbose=T, factory captures correctly all warning/errors but also shows all cats on screen. If I set verbose=F, factory misses important warnings coming via cat (even when blocking the function) and does not show cats on screen. The function is quite complex and I cannot change it. I would rather modify slightly factory so that cat messages are captured as warning (as it already happens) but are not shown on screen. – kalka Feb 26 '16 at 08:34
  • You can use `capture.output()` to capture `cat()` output, but really the function that you are calling should be modified to use stop / warning / message as appropriate. – Martin Morgan Feb 26 '16 at 14:02
  • how would I use capture.output()? I tried factory(capture.output(fun))(...) but this give an error as output ( "could not find function \"fun\""). I also tried capture.output(factory(fun)(...)) and this return a long text output without the output intended. Unfortunately I cannot change the function. It is quite complex for my competence and there is no way to know what messages the financial site will actually send. I get a mixture of intended output and many other less important messages... – kalka Feb 26 '16 at 15:47

1 Answers1

0

You need to set your options so that error messages aren't shown. In the body of the function you can call the following code:

options(show.error.messages= FALSE)

Don't forget to turn it into TRUE before leaving, it's always useful to see error messages.

PavoDive
  • 6,322
  • 2
  • 29
  • 55