Sink () doesn't work in tryCatch block

I am trying to close a log instance in a finally block like this:

logger <- file("all.Rout", open="wt")           
sink(logger, type="message")                                 

tryCatch({
    warning('test')
    message("A")
    log('a')
    message("B")
}, error = function(e) {
}, finally = {
    sink(type="message")
    close(logger)
})

      

However, it is only message("A")

saved in the log and nothing else. If I do the following, the problem is fixed:

logger <- file("all.Rout", open="wt")           
sink(logger, type="message")                                 

tryCatch({
    warning('test')
    message("A")
    log('a')
    message("B")
}, error = function(e) {
}, finally = {
})

sink(type="message")
close(logger)

      

However, I really need the closure to be in the block finally

so that I can view the logs if an error is made.

How to fix it?

+3


source to share


1 answer


The problem is that the default is not printed warnings

as they occur. They are piled up and then printed out when convenient. Therefore, R does not think the block finally

is a good time to print these warnings, because you are not inactive at that point and may not see them. One job is to change the setting to report all warnings as it happens, rather than waiting for the current call to complete. you can do it with this

logger <- file("log.txt", open="wt")           
sink(logger, type="message")                                 

tryCatch({
    ow<-options(warn=1)
    warning('test')
    message("A")
    log('a')
    message("B")
}, 
error = function(e) {
}, finally = {
    options(ow)
    sink(type="message")
    close(logger)
})

      

Here we change options()

at the beginning of the try block and then reset to them. Finally,



The contents of the log file are then

Warning in doTryCatch(return(expr), name, parentenv, handler) : test
A

      

In another method, you will notice that the messages are canceled even though the first warning. Again, R just waited until the end of the current call returned warning messages to you, and that was after completion tryCatch()

.

+2


source







All Articles