R doesn’t come with a built-in constructor function for conditions, but we can easily add one.

(Advanced R, by Hadley Wickham)

Actually, there is simpleCondition(), simpleError() and the like, but they don’t allow specifying an additional class. The functions in this package allow it:

library(condition)
cond <- new_error("Something went wrong", class = "oops")
cond
## <oops: Something went wrong>
is.error(cond)
## [1] TRUE

Everything is powered by an R6 generator class that creates condition class objects:

Condition
## <ConditionClassBase>
##   Inherits from: <ConditionClass>
##   Public:
##     as: NULL
##     class_name: condition
##     initialize: function () 
##     is: function (x, ...) 
##     new: function (message, call = NULL, class = NULL) 
##     parent: NULL
Error
## <ConditionClass>
##   Public:
##     as: function (x, ...) 
##     class_name: error
##     initialize: function (class_name, parent) 
##     is: function (x, ...) 
##     new: function (message, call = NULL, class = NULL) 
##     parent: environment

These condition objects can be used instead the plain functions:

Error$new("Plain error")
## <error: Plain error>

If a custom condition is used more than once, it is a good idea to formalize it:

Oops <- ConditionClass$new("oops", Error)
oops <- Oops$new("Something went wrong")
oops
## <oops: Something went wrong>
Oops$is(oops)
## [1] TRUE

A custom condition object inherits from its base:

Error$is(oops)
## [1] TRUE