Search code examples
rerror-handlingassertthat

Returning an error message other than the last one thrown in R


I have two functions that construct R S3 objects. One object encapsulates the other. When the user passes a bad num argument to fun2() it throws the error assertion in fun2(). I think it would be more informative for the user to see the message in fun1(). What are the options for preserving the message raised in fun1() and raising that instead of the message in fun2()?

fun1 <- function(num) {
  assert_that(num %% 2 == 0, msg = "num should be even")
  structure(num,
      class = "fun1-Class"
  )
}
fun2 <- function(text, num) {
  assert_that(class(num) == "fun1-Class", msg = "Bad Class")
  structure(list(text, num),
    class = "fun2-Class"
  )
}

fun1(1.2)
# Throws error "num should be even"

x <- fun2("myText", fun1(1.2))
# Throws error "Bad Class"

Traceback is below

 Error: Bad Class 
3.
stop(assertError(attr(res, "msg"))) 
2.
assert_that(class(num) == "fun1-Class", msg = "Bad Class") 
1.
fun2("text", fun1(1.2)) 

Solution

  • @aurèle answered this in the comments.

    This happens because of the lazy evaluation of function parameters. force(num) will change the behavior and evaluate the first constructor.