How can I make sure that after I “catch” an error and log it no further code steps are executed (I do not want to use q())?
My usage scenario is like this:
– do some calculations
– if error occurs log it
– stop executing any further steps in the code
I tried to solve this using code example below (print is used instead of true logging function):
handleMySimpleError<-function(e, text) {
# Let's log the error
print(paste0(text, ": ", e))
# This should stop execution of any further steps but it doesn't
stop("Now, stop. For real.")
}
print("Starting execution...")
tryCatch(
stop("My simple error."),
error=function(e) {handleMySimpleError(e, "could not finish due to")}, finnaly=NULL
)
print("Successfully ended execution...")
I somehow hoped that print(“Successfully ended execution…”) would never get executed… But, here is the output I get:
> handleMySimpleError<-function(e, text) {
+ # Let's log the error
+ print(paste0(text, ": ", e))
+ # This should stop execution of any further steps but it doesn't
+ stop("Now, stop. For real.")
+ }
>
> print("Starting execution...")
[1] "Starting execution..."
> tryCatch(
+ stop("My simple error."),
+ error=function(e) {handleMySimpleError(e, "could not finish due to")}, finnaly=NULL
+ )
[1] "could not finish due to: Error in doTryCatch(return(expr), name, parentenv, handler): My simple error.\n"
Error in handleMySimpleError(e, "could not finish due to") :
Now, stop. For real.
> print("Successfully ended execution...")
[1] "Successfully ended execution..."
How to prevent from print(“Successfully ended execution…”) being executed? What is the correct strategy to stop code processing after error is logged in error handler function?
Just wrap curly braces around it