Suppose I have two R files: correct.R
and broken.R
. What would be the best way of using tryCatch
to check for errors?
Currently, I 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've constructed the tryCatch
means that I have to interrogate the x
and y
objects to determine if there has been an error.
Is there a better way of doing this?
The question comes from teaching. 100 students upload their R scripts and I run the scripts. To be nice, I'm planning on creating a simple function that determines if their function sources correctly. It only needs to return TRUE or FALSE.
Try this:
> tryCatch(stop("foo"), error = function(e) {
+ cat(e$message, "\n")
+ FALSE
+ })
foo
[1] FALSE
Alternatively, you should consider Hadley's testthat
package:
> expect_that(stop("foo"), is_a("numeric"))
Error in is.vector(X) : foo
To expand upon mdsumner's point, this is a simple implementation.
sources_correctly <- function(file)
{
fn <- try(source(file))
!inherits((fn, "try-error"))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With