You can set opts_chunk$set(error = FALSE)
, then you will be able to run traceback()
when an error occurs. This requires you to run knitr in an interactive R session, though.
Question
How do I get better error reporting from knitr?
e.g. now knitr quits with:
Calls: knit ... lapply -> FUN -> lapply -> FUN -> rename -> <Anonymous>
When I run the same code interactively R quits with:
Calls: getSampleData ... lapply -> FUN -> lapply -> FUN -> rename -> <Anonymous>
Which is much better for understanding the problem - at least I know which function was throwing the error.
Ideally I would like also have the equivalent of traceback() appended.
La solution
Autres conseils
For the related problem where you actually want to display the error to the reader of your document, I wrote a wrapper function that computes and saves a traceback within a knitr document, and a replacement for traceback() that displays it. Here's the code:
saveTraceback <- local({
savedTraceback <- NULL
saver <- function(e) {
calls <- sys.calls()
deparsed <- lapply(calls, deparse)
deparsed <- deparsed[-length(deparsed)+0:1] # leave off last 2
lastjunk <- max(grep("withCallingHandlers", deparsed))
deparsed <- deparsed[-seq_len(lastjunk)]
savedTraceback <<- deparsed
}
function(expr)
withCallingHandlers(expr, error = saver)
})
traceback <- function() {
base::traceback(environment(saveTraceback)$savedTraceback)
}
You would use it like this. First display the code without executing it:
<<mycode,eval=FALSE>>=
f <- function() stop("this is an error")
g <- function() f()
g()
@
Then execute it in the saveTraceback()
function without displaying:
<<echo=FALSE>>=
saveTraceback({
<<mycode>>
})
@
And finally call traceback()
, which will display something like what the
user would have seen in the console.