Description Usage Arguments Details Note on backwards compatibility Note Examples
View source: R/Fixes-extensions.R
The regular base::tryCatch
calls a function whenever expr
generates an error, which means this function gets its own environment.
However, sometimes it's easier to evaluate any code in the same environment as expr
(see examples).
Therefore this extension can work with expressions as well, which are then evaluated in the calling context.
If this expression returns a function, then that function is called with the condition-object.
Note that 'expression' here is used in the sense of 'some R-code', so error=function(e) {e$message}
is seen as a very simple expression, which
returns a function, which is then called. This means that you can still use the same calls as in base::tryCatch
.
1 |
expr |
Expressions to evaluate that might throw an error |
... |
Handlers to call if expr throws a condition |
finally |
expression that is always evaluated before returning or exiting |
For use of the condition-object in the main expressions, you can access it under the name "cond" if there is no variable under that name yet.
If there is one, this variable is left as-is, and the current condition-object can be accessed with get('cond', parent.frame(2))
.
The latter form can always be used (for cases when you're unsure of its existence)
This function is meant as a stand-in replacement for base::tryCatch, but there are differences in the calling stack.
See for example the difference in the options you can choose from in the following calls:
base::tryCatch(stop(), error=function(e) recover())
vs
tryCatch(stop(), error=function(e) recover()
Therefore there may be some differences in debugging code as well, and code should not rely on any output
of parent.frame(n) or length(sys.calls()) etc.
All current variables are potentially modified by the condition-throwing expression, which may be very desirable (for debugging) or very undesirable/confusing (as some objects can be in an unexpected/corrupted state)
1 2 3 4 5 6 7 | errorlog <- character(0) # Or some other previous log
tryCatch({step <- 1;stop('SomeError');step <- 2},
warning=function(w) print(w),
error={errorlog <- c(errorlog, paste("\nError occured:\n", cond$message, "\nat step:", step))
step <- 0
function(e) {err <- getOption('error'); if(!is.null(err)) eval(err)}
})
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.