Structured, classed failures for R data and modelling code, in a format shared with the Python DataExcept package.
R already has classed conditions: errorCondition() and rlang::abort() both
create errors with a class and fields. What dataexcept adds is the part that
does not exist yet:
glm.fit non-convergence,
perfect separation, NAs introduced by coercion and others arrive as plain
simpleWarnings, recognisable only by their text, and that text is
translated into the session language. dataexcept recognises them through
R's own message catalogue, so the match works in any language.Credentials in URLs are removed before they reach a condition or an envelope, using the same rules as the Python package.
Documentation: https://diogoribeiro7.github.io/r-dataexcept/
# install.packages("pak")
pak::pak("DiogoRibeiro7/r-dataexcept@v0.4.2") # the latest release
pak::pak("DiogoRibeiro7/r-dataexcept") # the development version
dataexcept depends on base R (>= 4.1) and jsonlite.
After installation, open the local worked example with
vignette("structured-failures", package = "dataexcept") or find it with
browseVignettes("dataexcept"). The complete reference remains on MkDocs.
Constructors return a condition; stop() signals it. Handlers catch by class,
including a whole family through its parent class, and read the fields
directly.
library(dataexcept)
orders <- data.frame(id = 1:3, amount = c("10", "20", "30"))
check_amount <- function(df) {
if (!"amount" %in% names(df)) {
stop(missing_column_error("amount", dataframe = "orders"))
}
if (!is.numeric(df$amount)) {
stop(dtype_mismatch_error("amount", "numeric", class(df$amount)[1]))
}
invisible(df)
}
err <- tryCatch(check_amount(orders), dataexcept_data_frame_error = identity)
conditionMessage(err)
#> [1] "Column 'amount' has type character; expected numeric"
err$found
#> [1] "character"
dataexcept_classes() lists every type: data frame errors (missing column,
type mismatch, merge keys), data and modelling errors (loading, training,
convergence, prediction), data quality (format, schema, drift, leakage,
imbalance), model quality (evaluation, cross-validation, overfitting),
file, database, network, API and external service errors, and job and batch
failures. new_dataexcept_error() defines your own.
Every dataexcept error says whether retrying can help. The default is
conservative -- "unknown", with retryable NULL, which is deliberately not
FALSE -- and code that knows the backend's answer attaches it.
err <- api_error("https://api.example.com/v1/orders?page=2&api_key=abc123",
status_code = 503L)
err <- with_failure_metadata(
err,
failure_metadata("transient", retryable = TRUE, retry_after_seconds = 30)
)
is_retryable(err)
#> [1] TRUE
conditionMessage(err)
#> [1] "API call failed: https://api.example.com/v1/orders?page=2&api_key=*** (status 503)"
condition_to_json() writes any condition -- a dataexcept error, a base R
simpleError, an rlang error -- with its chain of causes:
cat(condition_to_json(err, pretty = TRUE))
{
"type": "ApiError",
"module": "dataexcept",
"message": "API call failed: https://api.example.com/***?page=2&api_key=*** (status 503)",
"failure": {
"kind": "transient",
"retryable": true,
"retry_after_seconds": 30
},
"attributes": {
"endpoint": "https://api.example.com/***?page=2&api_key=***",
"status_code": 503
}
}
Envelopes are strict JSON and follow the published schema,
envelope-1.0.0.json, which ships with the package (envelope_schema()).
Text leaving R is redacted again, this time including URL paths.
envelope_to_condition() reads an envelope from either language. A Python
MissingColumnError becomes an R dataexcept_missing_column_error, so the
handler written for local failures catches it:
json <- '{
"type": "MissingColumnError",
"module": "dataexcept.pandas_exceptions",
"message": "[MissingColumnError] Missing required column customer_id",
"failure": {"kind": "unknown", "retryable": null, "retry_after_seconds": null},
"attributes": {"column": "customer_id", "dataframe": null}
}'
cnd <- envelope_to_condition(json)
tryCatch(stop(cnd), dataexcept_data_frame_error = function(e) e$column)
#> [1] "customer_id"
Written back, a condition read this way reproduces its envelope exactly, and
validate_envelope() checks a payload against the schema's rules without
needing a JSON Schema validator.
An operation context records where a failure happened, separately from what
failed, with the fields and rules of the Python package's OperationContext.
condition_to_event_json() writes both as one line of JSON for a log:
context <- operation_context(system = "batch", operation = "settle_invoices", job_id = "job-42")
tryCatch(
settle_invoices(),
dataexcept_error = function(e) {
cat(condition_to_event_json(e, operation_context = context), "\n", file = stderr())
stop(e)
}
)
With the r-lib otel package, record_otel_exception()
records a failure on the active span, with the attribute names the Python
package uses, and operation_context_from_otel() puts the span's trace and
span IDs into the context so logs and traces correlate. Recording through
dataexcept keeps credentials out of the trace: the otel SDK records an
exception by printing the condition, unredacted, and dataexcept's attributes
replace those fields.
For a Node.js service that logs with Pino, condition_to_pino_json() writes
the failure in the shape Pino logs errors -- the Pino profile the Python
package publishes -- so an R job's failures read like any other in the same
log stream.
separated <- data.frame(y = c(0, 0, 1, 1), x = 1:4)
fit <- withCallingHandlers(
with_classed_warnings(glm(y ~ x, family = binomial, data = separated)),
dataexcept_separation_warning = function(w) {
message("Perfect separation in the logistic fit")
invokeRestart("muffleWarning")
}
)
#> Perfect separation in the logistic fit
The same code works in a German session, where the warning reads
glm.fit: Angepasste Wahrscheinlichkeiten mit numerischem Wert 0 oder 1
aufgetreten: each warning is compared with its template translated through the
catalogue R used to write it. Besides base R and stats, the rules cover
survival's Cox models and lme4's convergence checks, and a warning that
carries values, such as the iterations kmeans() ran, has them as fields.
classed_warning_rules() lists what is recognised. A handler can also fail
closed, turning non-convergence into a convergence_error() with the warning
as its cause.
inst/schema/ are the Python
package's. The tests read every fixture into R and write it back unchanged,
and project every one to the Pino profile exactly as Python does.validate_envelope() is tested against the verdicts of a JSON Schema
validator on valid and invalid payloads.jsonschema, and a weekly job regenerates the fixtures from
DataExcept's main branch and fails if anything has moved.Differences from the Python package are deliberate and few:
dataexcept_data_frame_error and
dataexcept_file_error, where Python has PandasError and CustomIOError.
Leaf types have the same names in both languages.[TypeName] prefix some Python classes add;
the envelope's type field already says it."dataexcept" as the module of a dataexcept
condition. Python uses its module path, such as
"dataexcept.pandas_exceptions". The reader accepts both.rlang provides classed errors, chained causes and backtraces, and dataexcept works with it: an rlang error serialises like any other condition, with its parent chain as the envelope's causes. dataexcept does not replace rlang; it adds the cross-language format and the vocabulary.
Bug reports, condition types and warning rules are welcome. See contributing guide for the development setup and the checks a pull request needs, and security policy for reporting a vulnerability privately.
Please note that this project is released with a Contributor Code of Conduct. By participating in it you agree to abide by its terms.
citation("dataexcept")
Citation metadata is also available in the repository.
MIT © Diogo Ribeiro