捕获所有异常

异常处理

check_data <- function(data) {
  if (is.null(data)) {
    stop(errorCondition("data is NULL",
                        class = "IsNullError"))
  }
  if (length(data) == 0) {
    stop(errorCondition("data is empty",
                        class = "IsEmptyError"))
  }
}

# The first class of the condition is its own name
error_class <- tryCatch(check_data(NULL),
                        error = \(e) class(e)[1])
# error_class = IsNullError

cat("error_class =", error_class, "\n")