1

The knitr would always evaluate the R code before formatting the output, so just wondering how can I know whether the R code evaluation has error. Thanks

zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • 2
    **knitr** uses the **evaluate** package to run each chunk, catching and handling any warnings and errors. [Here](https://stackoverflow.com/a/14613363/980833) is an old answer of mine that might help you to see how it does so. – Josh O'Brien Jan 17 '18 at 01:34

1 Answers1

1

Basically it boils down to three lines of code in the evaluate package. The key is withCallingHandlers(), which can be used to capture errors, messages, and warnings, etc. A minimal example:

withCallingHandlers(1 + 'a', error = function(e) {
  cat('An error occurred! The error object is:\n')
  str(e)
})

If you don't want the error to halt R, you can wrap the code in try().

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419