Using tryCatch and source

Suppose I have two R files: correct.Rand broken.R. What would be the best way to use tryCatchfor error checking?

I currently have

> x = tryCatch(source("broken.R"), error=function(e) e)
> x
 <simpleError in source("broken.R"): test.R:2:0: unexpected end of input
  1: x = {
     ^>
> y = tryCatch(source("correct.R"), error=function(e) e)
> y
 $value
 [1] 5

 $visible
 [1] FALSE

However, the way I built tryCatchmeans that I have to interrogate the objects xand yto determine if there was an error.

Is there a better way to do this?


The question comes from the doctrine. 100 students upload their R-scripts and I run the scripts. To be nice, I plan to create a simple function that correctly determines whether their sources are functioning properly. He only needs to return TRUE or FALSE.

+5
source share
3

, , , $visible:

y <- tryCatch(source("broken.R"), error=function(e) e)
works <- !is.null(y$visible) #y$visible would be null if there were an error

, ? ( lapply), :

for(i in 1:length(students)) {
  works[i] <- !is.null(tryCatch(source(student_submissions[i]), error=function(e) e)$visible)
}
+2

:

> tryCatch(stop("foo"), error = function(e) {
+ cat(e$message, "\n")
+ FALSE
+ })
foo 
[1] FALSE

Hadley testthat:

> expect_that(stop("foo"), is_a("numeric"))
Error in is.vector(X) : foo
+4

To expand the mdsumner point, this is a simple implementation.

sources_correctly <- function(file)
{
  fn <- try(source(file))
  !inherits((fn, "try-error"))
}
+2
source

All Articles