I want to capture an error from D%4 and move on. The error is:
Error: unexpected input in "D%4"
Typically if a function is being called the following works:
capture_warn_error <- function(x){
tryCatch({
x
}, warning = function(w) {
w
}, error = function(e) {
e
})
}
capture_warn_error(D%4)
But the no recovery is possible as `D%4 shuts down everything immediately:
## > capture_warn_error(D%4)
## Error: unexpected input in "capture_warn_error(D%4)"
Is there anyway to capture such a stubborn beast and move on? I know D%4 isn't an object but this works for other non objects:
capture_warn_error(means)
## <simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'means' not found>
It's be nice to:
Understand why D%4 is unrecoverable vs means
Find a way to recover still and capture D%4's error
As others have stated it is because text typed at the console gets passed to the parser. D%4 fails the rigid test of being valid R expression, because a single % is not valid inside an R name (although it would create a token that would be interpreted as a user defined function if there were a closing %) and % is also not a function name (although%% is). The error occurs in the processing of the argument to your function and so it never reached the internal tryCatch-call. I originally didn't get the idea that you wanted to parse this input as R code, so thought that simply wrapping readline as the single argument to be be input may satisfy:
mfun <- function( x=readline(">>+ ") ){ print(x) }
mfun()
#-----screen will display--------
>>+ D%4
[1] "D%4"
If I'm wrong about your intent, as it appears on a re-read of the question, then this would build that input mechanism into your capture_error function. This brings those characters in as unparsed text and then does the parse-eval within the tryCatch enclosure:
> capture_warn_error <- function(x=readline(">>+ ")){
+ tryCatch({ eval(parse(text=x))
+
+ }, warning = function(w) {
+ w
+ }, error = function(e) {
+ e
+ })
+ }
> capture_warn_error(D%4)
Error: unexpected input in "capture_warn_error(D%4)"
> capture_warn_error()
>>+ D%4
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: D%4
^>
> err <- capture_warn_error()
>>+ D%4
> err
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: D%4
^>
> err <- capture_warn_error()
>>+ D %% 4
> err
<simpleError in D%%4: non-numeric argument to binary operator>
> err <- capture_warn_error()
>>+ 4 %smthg% 2
> err
<simpleError in eval(expr, envir, enclos): could not find function "%smthg%">
As demonstrated above, it does require that you not provide any input in the argument list to the function call, but rather make the capture-call with an empty argument list.
You could set up a function to capture input and parse it, wrapping it in your capture_warn_error function.
getfunction <- function(){
x<-readline()
if(x == "exitnow"){return("bye!")}
print(capture_warn_error(eval(parse(text = x))))
getfunction()
}
They'll now be typing at a non-console prompt, but it will work okish - assignments will need work.
1+1
[1] 2
d%e
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: d%e
^>
exitnow
[1] "bye!"
I think this works for capturing the error, although it's a bit convoluted.
a <- try(eval(parse(text="D%4")))
Related
I want to use quoted arguments in my function and I would like to allow the user to specify that they don't want to use the argument by setting it to NULL. However, rlang::ensym throws an error when it receives a NULL argument. Here is my code:
f <- function(var){
rlang::ensym(var)
return(var + 2)
}
# This works
variable = 2
f(variable)
# This throws an error
f(NULL)
The error message is:
Error: Only strings can be converted to symbols
I already tried adding an if-clause with is.null(var) before the expression with rlang::ensym, but of course, this doesn't work as the variable is not yet quoted at this time.
How can I check that the supplied quoted variable is NULL in order to handle it differently?
If you need to allow for NULL, it's more robust to use quosures first. Then you can inspect the quosure to see what's inside. For example
f <- function(var){
var <- rlang::enquo(var)
if (rlang::quo_is_null(var)) {
var <- NULL
} else if (rlang::quo_is_symbol(var)) {
var <- rlang::get_expr(var)
} else {
stop(paste("Expected symbol but found", class(rlang::get_expr(var))))
}
return(var)
}
And that returns
f(variable)
# variable
f(NULL)
# NULL
f(x+1)
# Error in f(x + 1) : Expected symbol but found call
Or you can use whatever logic is appropriate for your actual requirements.
I'm working on an R package where the same input-checking functions are called by multiple "actual" functions that are exported to users. If I use a simple stop() call, the error message is going to say that an error occurred in the input-checking function, which is not that useful...
I thought I'd get around this by wrapping the call to the input-checking function inside a tryCatch(), and then handling the error in the outer function. This does mostly what I want, but doesn't quite give the output that I'd like. The closest I've come is the following:
f <- function(i) {
tryCatch({
check_input(i)
}, error = function(e) stop("in f: ", e$message, call. = FALSE)
)
}
check_input <- function(i) {
if(i < 0)
stop("i is negative, value given was ", i)
}
f(-1)
# Error: in f: i is negative, value given was -1
Ideally, I'd like the error message to be
Error in f: i is negative, value given was -1
, which would be the case if stop were called within f() instead of check_input().
Here's how you can grab the name of the function from the call stack and paste it in to the error message
f <- function(i) {
check_input(i)
}
g <- function(i) {
check_input(i)
}
check_input <- function(i, from=deparse(sys.calls()[[sys.nframe()-1]][[1]])) {
getmsg <- function(m) ifelse(!is.null(from), paste0("in ", from, ": ", m), m)
if(i < 0)
stop(getmsg(paste0("i is negative, value given was ", i)), call. = FALSE)
}
f(-1)
# Error: in f: i is negative, value given was -1
g(-1)
# Error: in g: i is negative, value given was -1
You could also call check_input(i, from="otherfunction") to show whatever function name you want or check_input(i, from=NULL) to suppress the function name.
Begin a new R session with an empty environment. Write a series of functions with a parameter that is to be used as the value of the times parameter in a call to rep().
f <- function(n) {
rep("hello", times = n)
}
f(x)
One expect this to fail, and indeed one gets:
# Error in f(x) : object 'x' not found
Modify the function a bit:
f2 <- function(n) {
ls.str()
rep("hello", times = n)
}
f2(x)
As expected, it still fails:
# Error in f2(x) : object 'x' not found
Modify a bit more (to see the environment in the console):
f3 <- function(n) {
print(ls.str())
rep("hello", times = n)
}
f3(x)
I still expect failure, but instead get:
## n : <missing>
## [1] "hello"
It is as if the call to print() makes rep work as though times were set to 1.
This is not an answer, but too long to post as a comment. A minimal reproducible example is:
f3 <- function(n) {
try(get("n", environment(), inherits=FALSE))
rep("hello", times = n)
}
f3(x)
## Error in get("n", environment(), inherits = FALSE) : object 'x' not found
## [1] "hello"
The following is speculative and based on loosely examining the source for do_rep. get starts the promise evaluation, but upon not finding the "missing" symbol appears to leave the promise partially unevaluated. rep, being a primitive, then attempts to operate on n without realizing that it is a partially evaluated promise and basically that leads implicitly to the assumption that 'n == 1'.
Also, this shows that the promise is in a weird state (have to use browser/debug to see it):
f3a <- function(n) {
try(get("n", environment(), inherits=FALSE))
browser()
rep("hello", times = n)
}
f3a(x)
## Error in get("n", environment(), inherits = FALSE) : object 'x' not found
## Called from: f3a(x)
# Browse[1]> (n)
## Error: object 'x' not found
## In addition: Warning message:
## restarting interrupted promise evaluation
## Browse[1]> c
## [1] "hello"
I received earlier today a report that the bug has been fixed in R-devel and R-patched.
The issue was that the test for missingness in the R sources did not consider the case of an interrupted promise evaluation. A fix has been committed by Luke Tierney and can be seen on GitHub.
f4 <- function(n) {
print('test')
print(ls.str())
print('end test')
rep("hello", times = n)
}
f4(x)
## [1] "test"
## n : <missing>
## [1] "end test"
## [1] "hello"
There's something within print.ls_str, from Frank's test on chat the follwing code exhibit the same problem:
f6 <- function(n) {
z = tryCatch(get("n", new.env(), mode = "any"), error = function(e) e)
rep("A", n)
}
Digging a little inside R source I found the following code
# define GET_VALUE(rval) \
/* We need to evaluate if it is a promise */ \
if (TYPEOF(rval) == PROMSXP) { \
PROTECT(rval); \
rval = eval(rval, genv); \
UNPROTECT(1); \
} \
\
if (!ISNULL(rval) && NAMED(rval) == 0) \
SET_NAMED(rval, 1)
GET_VALUE(rval);
break;
case 2: // get0(.)
if (rval == R_UnboundValue)
return CAD4R(args);// i.e. value_if_not_exists
GET_VALUE(rval);
break;
}
return rval;
}
#undef GET_VALUE
I'm quite surprised this compile properly, as far as I remember (my C is quite far behind) #define doesn't allow spaces between the # and define.
After digging for that, I'm wrong, from gcc doc:
Whitespace is also allowed before and after the `#'.
So there's probably something around this part of code, but that's above my head to pinpoint what exactly.
Displaying error locations with options(show.error.locations = TRUE) doesn't seem to work when handling exceptions with tryCatch. I am trying to display location of the error but I don't know how:
options(show.error.locations = TRUE)
tryCatch({
some_function(...)
}, error = function (e, f, g) {
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
})
If I then look at the variable e, the location doesn't seem to be there:
> str(e)
List of 2
$ message: chr "missing value where TRUE/FALSE needed"
$ call : language if (index_smooth == "INDEX") { rescale <- 100/meanMSI[plotbaseyear] ...
- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
If I don't trap the error, it is printed on the console along with source file and line number. How to do it with tryCatch?
Context
As noted by Willem van Doesburg, it is not possible to use the traceback() function to display where the error occured with tryCatch(), and to my knowledge there is currently no practical way to store the position of the error with base functions in R while using tryCatch .
The idea of a separate error handler
The possible solution I found consists of two parts, the main one is writing an error handler similar to that of Chrispy from "printing stack trace and continuing after error occurs in R" which produces a log with the position of the error.
The second part is capturing this output into a variable, similarly to what was suggested by Ben Bolker in "is it possible to redirect console output to a variable".
The call stack in R seems to be purged when an error is raised and then handled (I might be wrong so any information is welcomed), hence we need to capture the error while it is occuring.
Script with an error
I used an example from one of your previous questions regarding where and R error occured with the following function stored in a file called "TestError.R" which I call in my example bellow:
# TestError.R
f2 <- function(x)
{
if (is.null(x)) "x is Null"
if (x==1) "foo"
}
f <- function(x)
{
f2(x)
}
# The following line will raise an error if executed
f(NULL)
Error tracing function
This is the function I adapted form Chrispy's code as I mentionned above.
Upon execution, if an error is raised, the code underneath will print where the error occured, in the case of the above function, it will print :
"Error occuring: Test.R#9: f2(x)" and "Error occuring: Test.R#14: f(NULL)" meaning the error result from a trouble with the f(NULL) function at line 14 which references the f2() function at line 9
# Error tracing function
withErrorTracing = function(expr, silentSuccess=FALSE) {
hasFailed = FALSE
messages = list()
warnings = list()
errorTracer = function(obj) {
# Storing the call stack
calls = sys.calls()
calls = calls[1:length(calls)-1]
# Keeping the calls only
trace = limitedLabels(c(calls, attr(obj, "calls")))
# Printing the 2nd and 3rd traces that contain the line where the error occured
# This is the part you might want to edit to suit your needs
print(paste0("Error occuring: ", trace[length(trace):1][2:3]))
# Muffle any redundant output of the same message
optionalRestart = function(r) { res = findRestart(r); if (!is.null(res)) invokeRestart(res) }
optionalRestart("muffleMessage")
optionalRestart("muffleWarning")
}
vexpr = withCallingHandlers(withVisible(expr), error=errorTracer)
if (silentSuccess && !hasFailed) {
cat(paste(warnings, collapse=""))
}
if (vexpr$visible) vexpr$value else invisible(vexpr$value)
}
Storing the error position and the message
We call the script TestError.R above and capture the printed output in a variable, here called errorStorage with which we can deal later on or simply display.
errorStorage <- capture.output(tryCatch({
withErrorTracing({source("TestError.R")})
}, error = function(e){
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
}))
Hence we keep the value of e with the call and message as well as the position of the error location.
The errorStorage output should be as follow:
[1] "[1] \"Error occuring: Test.R#9: f2(x)\" \"Error occuring: Test.R#14: f(NULL)\""
[2] "ERROR: argument is of length zero "
[3] "in if (x == 1) \"foo\""
Hoping this might help.
You can use traceback() in the error handler to show the call stack. Errors in a tryCatch don't produce line numbers. See also the help on traceback. If you use your tryCatch statements defensively, this will help you narrow down the location of the error.
Here is a working example:
## Example of Showing line-number in Try Catch
# set this variable to "error", "warning" or empty ('') to see the different scenarios
case <- "error"
result <- "init value"
tryCatch({
if( case == "error") {
stop( simpleError("Whoops: error") )
}
if( case == "warning") {
stop( simpleWarning("Whoops: warning") )
}
result <- "My result"
},
warning = function (e) {
print(sprintf("caught Warning: %s", e))
traceback(1, max.lines = 1)
},
error = function(e) {
print(sprintf("caught Error: %s", e))
traceback(1, max.lines = 1)
},
finally = {
print(sprintf("And the result is: %s", result))
})
When a call exists of multiple lines, a potential error only includes the first line of match.call() resulting in some lost information and an incomplete sentence. A simple example:
#proper error message:
runif(n=1, k=5)
#incomplete error message:
runif(n=1, k={5})
What would be a way to get R to include the full call to the error message (maybe by collapsing the multiple lines or so)? I am mostly interested in using this in a tryCatch setting.
I had a go at investigating the error object in a tryCatch setting via:
tryCatch( runif(n=1,k={5}),
error = function(e) recover() )
And then selected the 4th environment (value[[3]](cond)) to examine e.
I noticed that e$call was:
Browse[1]> e$call
runif(n = 1, k = {
5
})
So it seems that the error message just uses that first line.
You can collapse all the lines together with:
Browse[1]> paste(deparse(e$call),collapse='')
[1] "runif(n = 1, k = { 5})"
So you could try something like:
tryCatch( runif(n=1,k={5}),
error = function(e) {
cat(sprintf('Error in %s: %s\n',
paste(deparse(e$call),collapse=''),
e$message))
} )
But this doesn't fix up the error message itself, just the call leading up to it:
Error in runif(n = 1, k = { 5}): unused argument(s) (k = {
So the 'Error in xxx' is complete, but the 'unused argument(s) xxx' is still not. It's a start, but not all the way there.
I'm not sure how to improve on this (and am also interested to know if it's possible).