I have a generic function to catch all the exceptions included in my package logR::tryCatch2 , defined as:
tryCatch2 <- function(expr){ V=E=W=M=I=NULL e.handler = function(e){ E <<- e NULL } w.handler = function(w){ W <<- c(W, list(w)) invokeRestart("muffleWarning") } m.handler = function(m){ attributes(m$call) <- NULL M <<- c(M, list(m)) } i.handler = function(i){ I <<- i NULL } V = suppressMessages(withCallingHandlers( tryCatch(expr, error = e.handler, interrupt = i.handler), warning = w.handler, message = m.handler )) list(value=V, error=E, warning=W, message=M, interrupt=I) }
As you can see in the last line, it returns a list that is more or less described independently.
This makes the real response to exceptions delayed after calling tryCatch2 simple !is.null :
f = function(){ warning("warn1"); warning("warn2"); stop("err") } r = tryCatch2(f()) if(!is.null(r$error)) cat("Error detected\n") # Error detected if(!is.null(r$warning)) cat("Warning detected, count", length(r$warning), "\n") # Warning detected, count 2
It works as expected, I can react with my own code. But in some cases, I would like to not stop the interrupt process, which is also caught. At the moment, it seems to me that I need to add an additional parameter to tryCatch2 , which will control if interrupts should be catchy or not. So the question asks about some invokeInterrupt function that I could use as follows:
g = function(){ Sys.sleep(60); f() } r = tryCatch2(g())
I think that if R is able to catch one, he should also be able to call him. How can I achieve invokeInterrupt functionality?
r try-catch
jangorecki Sep 28 '15 at 10:14 2015-09-28 10:14
source share