rr-markdown

Store chunk name when error occurs rendering markdown document


I've got a Rmarkdown document that I recursively run over a set of input parameters. I would need to fetch a error description and where it has occured. Cannot manage to pull the chunk name (it is written in console on error though).

tryCatch({
      render("my_Rmarkdown_doc.Rmd"),
             output_file = paste0(print_path, "doc_", i, ".html"),
             params = inpar[i, ])  
    },error = function(e) {
      message <- conditionMessage(e)
      new_message <- data.frame(message = message)
      message_df <<- rbind(message_df , new_message)  
    })

Here's a description of the console

processing file: my_Rmarkdown_doc.Rmd
  |...........................................                                                                                                                                                                                                                                                                          |  14% [chunk_no2]          
Quitting from lines 56-78 [chunk_no2] (my_Rmarkdown_doc.Rmd)

How can I pull the chunk name i.e. in this case "chunk_no2" and store it along with error message in message_df?


Solution

  • In a chunk, the chunk name is available as knitr::opts_current$get("label"). I think that is not available in your error handler, but you could write a hook function (see https://yihui.org/knitr/hooks/#chunk-hooks) that saved the label before trying to execute every chunk, and include the saved value in your message_df. In hook functions, the opts_current values are stored in the options argument.

    For example, use this setup in your document:

    ```{r setup and data import, include=FALSE}
    library(knitr)
    hook_chunkname = function(before, options, envir, name, ...) {
      if (before) {
        saved_chunk <<- options$label
      } 
    }
    knit_hooks$set(chunkname = hook_chunkname)
    opts_chunk$set(chunkname = TRUE)
    ```
    

    and run the documents using code like this:

    message_df <- data.frame(message=character(),
                             chunk=character())
    
    saved_chunk <- "Initial value"
    
    tryCatch({
      rmarkdown::render("Untitled.Rmd")  
    },error = function(e) {
      message <- conditionMessage(e)
      new_message <- data.frame(message = message, chunk = saved_chunk)
      message_df <<- rbind(message_df , new_message)  
    })