Home Q&A Thread

put tryCatchLog in the knitr evaluate.inline hook

th-tsai th-tsai 2y ago

I am recently working on a task to catch any message (TRACE, DEBUG, INFO, WARN, ERROR, or FATAL) in the rmarkdown while rendering it.

My first idea was to put render inside tryCatchLog like tryCatchLog(render("my.rmd")). However, this method cannot get any message within the rmd.

Thus, I came up with the second idea. I try to insert the tryCatchLog in the evaluate.inline knitr::hook setting. I expect every line of code will be evaluated under tryCatchLog.

knitr::knit_hooks$set( evaluate.inline = 
    function (code, envir = knit_global()) {
        v = withVisible(tryCatchLog(eval(parse_only(code), envir = envir)))  # add tryCatchLog here 
        if (v$visible) 
            knit_print(v$value, inline = TRUE, options = opts_chunk$get())
    }
)

Nevertheless, this doesn't work alongside what I expect neither. It seems like the file is knit as usual (no tryCatchLog in the evaluate.inline).

Is that I misunderstand the mechanism of evaluate.inline?

I appreciate any comment or explanation!

1 Reply

yihui yihui 2y ago

The evaluate.inline hook only works for inline R expressions (`r `). I think you need to insert your function in both evaluate.inline and evaluate:

My first idea was to put render inside tryCatchLog like tryCatchLog(render("my.rmd")). However, this method cannot get any message within the rmd.

To make that work, you must use the chunk options error = FALSE, message = NA, and warning = NA. If you can't set them inside the Rmd document, you may set

options(knitr.chunk.error = FALSE, knitr.chunk.message = NA, knitr.chunk.warning = NA)

before calling rmarkdown::render().

Sign in to join the discussion

Sign in with GitHub