When writing R code to be used in production systems that work
with user supplied input, it is important to enclose chunks of code inside
of a try()
block. It is equally important to generate error log
messages that can be found and understood during an autopsy when something
fails
At Mazama Science we have our own internal standard for how to do error handling in a manner that allows us to quickly navigate to the source of errors in a production system.
The example section contains a snippet showing how we use this function.
stopOnError(result, err_msg = "")
result | Return from a |
---|---|
err_msg | Custom error message. |
Issues a stop()
with an appropriate error message.
if (FALSE) { library(MazamaCoreUtils) logger.setup() # Arbitrarily deep in the stack we might have: myFunc <- function(x) { a <- log(x) } userInput <- 10 result <- try({ myFunc(x=userInput) }, silent=TRUE) stopOnError(result) userInput <- "ten" result <- try({ myFunc(x=userInput) }, silent=TRUE) stopOnError(result) result <- try({ myFunc(x=userInput) }, silent=TRUE) stopOnError(result, "Unable to process user input") }