When I use tryCatch
, I can define an error handler and use conditionCall
to determine the call that caused the error. For instance,
tryCatch(
eval(parse(text="prnit('Hello')")),
error=function(e) {
cl <- conditionCall(e)
#...
})
Can I get to the bad call on the R prompt? Until now, I found only this solution:
> err_hdl <- function() {
file1 <- tempfile("Rrawhist")
savehistory(file1)
rawhist <- readLines(file1)
unlink(file1)
cat("Error : ", tail(rawhist,1), "\n")
return(TRUE)
}
> options(error=err_hdl)
> prnit("Hello")
but I believe there must be a more straightforward way..
Any hint appreciated!
I put out a bounty. The first answer that implements the behaviour of the err_hdl
function above without file I/O that is platform independent will be accepted.
Edit -- the code above seems only to work on windows. I am looking for the input that raised the error.
It looks like dump.frames
can be told not to dump to a file but rather to an object in the .GlobalEnv
. However, I haven't tested it on anything but a Mac. Would the following help?
err_hdl2 <- function() {
dump.frames("theErr", to.file = FALSE)
cat("What happened?\n", attr(theErr,"error.message"), "\nOh.\n")
}
options(error = err_hdl2)
> prnit(dt)
Error: could not find function "prnit"
What happened?
Error: could not find function "prnit"
Oh.
There might be a drawback to creating the object theErr
in the global environment, I suppose.
> theErr
$`function ()
{
dump.frames("theErr", to.file = FALSE)
cat("What`
<environment: 0x1030fe140>
attr(,"error.message")
[1] "Error: could not find function \"prnit\"\n"
attr(,"class")
[1] "dump.frames"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With