[R] A question on generating Error message upon Timeout

Christofer Bogaso bog@@o@chr|@to|er @end|ng |rom gm@||@com
Thu May 9 21:36:47 CEST 2019


Hi,

I have created a function called myFn() which should be acting as below:

1. If function takes too long, then it will timeout and a specific message
will be displayed
2. This function may generate error on its own, so if it evaluates before
that specific time and fails then another specific message will be displayed
3. Within that specific time, if that function successfully run then the
result will be displayed.

To implement above strategy my function is as follows:


*library(R.utils)*
*myFn = function(n) {*
* n_Try = try({*
* if (n == 1) {Sys.sleep(10); Res = -123}*
* if (n == 2) stop()*
* if (n > 2) Res = 1:5 *
* }, silent = TRUE)*
* if (class(n_Try) == 'try-error') {*
* return("ERROR : Good Error.")*
* } else {*
* return(Res)*
* }*
* }*

Below is for case #1

*aa = *
*tryCatch({*
*  res <- withTimeout({*
*    myFn(1)*
*  }, timeout = 2, onTimeout = 'error')*
*}, error = function(ex) {*
*  ("Timeout Error")*
*}); aa*

I was expecting to get the expression for *aa* as *"Timeout Error"*,
however I am getting *"ERROR : Good Error."*. This is not going with my plan

Also, I dont think this function getting timeout just after 2 sec, appears
like it is evaluating for longer time

However for *myFn(2)*, I am getting right message as "*"ERROR : Good
Error."*"

*aa = *
*tryCatch({*
*  res <- withTimeout({*
*    myFn(2)*
*  }, timeout = 2, onTimeout = 'error')*
*}, error = function(ex) {*
*  ("Timeout Error")*
*}); aa*

So clearly my strategy is failing for *myFn(1)*. Any pointer where I was
wrong?

	[[alternative HTML version deleted]]



More information about the R-help mailing list