Exception handling and unwinding packets in R

To set up a compatible exception handling interface for my colleagues and my R scripts, I would like to use the following tryCatch structure.

  • An external tryCatch is wrapped around a given R script. It is used to catch and handle fatal errors requiring cancellation of the script.
  • Custom tryCatch commands in user scripts. They should catch and possibly handle
    • 2. non-fatal errors when there is no abortion script needed
    • 2b. fatal-errors, which require the script to break. The error is handled by an external tryCatch [see 1.]
    • 2s fatal errors with additional error information. Error handled by external tryCatch.

The following code is a way to implement these functions. However, since I am not an expert in the field of R, I would like to ask if this is a good approach. In particular:

Q1. Should you specify an error handler in the internal tryCatch and wait for the external tryCatch to handle this error (see Above 2b and the code below)?

Q2. Resets the same error (see 2c above / below) inside the handler correctly / is it considered a good coding style?

Thanks!

#outer tryCatch, see 1. tryCatch({ #user code block #2a. user specific tryCatch, object "vec" not defined tryCatch(print(vec),error=function(e) {print("Non-fatal error. Script execution continued.");print(e);}) #2b. user specific tryCatch tryCatch(vec*2) #2c. user specific tryCatch tryCatch(vec*parameter1, error=function(e) {print("Additional fatal error information. Script execution aborted.");stop(e);}) #end of user code block }, #outer tryCatch error handler in order to handle fatal errors error=function(e) {print("Fatal error");print(e);} ) 
+4
source share
1 answer

It is perfect to catch only some errors, leaving others to the external handler or no handler at all. The error system is quite a bit more flexible than commonly used, so you can create your own type of error to re-throw the error

 ourError <- function(original, message, class="ourError") { msg <- paste(message, conditionMessage(original), sep="\n ") structure(list(message = msg, call = conditionCall(original)), class = c(class, class(original))) } 

and throw and / or process that

 tryCatch(vec*parameter1, error=function(e) { err <- ourError(e, "addition fatal info; script aborted") stop(err) }) 

One of the advantages of this is that you can specify additional types of behavior in the top-level handler using the class returned by ourError()

 tryCatch({ tryCatch(stop("oops"), error=function(e) { err <- ourError(e, "addition fatal info; script aborted", c("fatal", "ourError")) stop(err) }) }, ourError=function(err) { message("We caught but didn't handle this:\n", err) }, error =function(err) { message("This one got away: ", err) }) 
+4
source

Source: https://habr.com/ru/post/1437162/


All Articles