Skip to content

Instantly share code, notes, and snippets.

@J-Moravec
Created September 17, 2024 20:10
Show Gist options
  • Save J-Moravec/27ce2eaee75504febb8ab1015bc24f6d to your computer and use it in GitHub Desktop.
Save J-Moravec/27ce2eaee75504febb8ab1015bc24f6d to your computer and use it in GitHub Desktop.
An example of subclassing conditions and then handling conditions of only a particular class.
# constructor based on the simpleError function
my_error = function(message, call = NULL){
class = c("my_error", "error", "condition")
structure(
list(as.character(message), call = call),
class = class
)
}
# my_error still needs to be signaled with stop():
my_error("this is an object of class \"my_error\", subclass of \"error\") |> stop()
# now it can be specifically handled in tryCatch or withCallingHandlers
tryCatch(
# expression
my_error("some message") |> stop(),
# we handle these conditions
my_error = functon(e){ paste0("We caught error of class \"my_error\" with message: ", conditionMessage(e) }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment