## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----classed-errors-----------------------------------------------------------
library(dataexcept)

validate_orders <- function(orders) {
  if (!"customer_id" %in% names(orders)) {
    stop(missing_column_error("customer_id", dataframe = "orders"))
  }
  invisible(orders)
}

orders <- data.frame(amount = c(10, 20, 30))
caught <- tryCatch(
  validate_orders(orders),
  dataexcept_data_frame_error = identity
)

stopifnot(inherits(caught, "dataexcept_missing_column_error"))
conditionMessage(caught)
caught$column

## ----failure-metadata---------------------------------------------------------
remote_failure <- api_error(
  "https://api.example.com/v1/orders?api_key=SECRET_VALUE",
  status_code = 503L
)
remote_failure <- with_failure_metadata(
  remote_failure,
  failure_metadata("transient", retryable = TRUE, retry_after_seconds = 15)
)

stopifnot(isTRUE(is_retryable(remote_failure)))
condition_failure(remote_failure)$retry_after_seconds

## ----write-envelope-----------------------------------------------------------
payload <- condition_to_json(remote_failure, pretty = TRUE)
stopifnot(is_envelope(payload))
stopifnot(!grepl("SECRET_VALUE", payload, fixed = TRUE))
cat(payload)

## ----read-envelope------------------------------------------------------------
restored <- envelope_to_condition(payload)
stopifnot(inherits(restored, "dataexcept_api_error"))
is_retryable(restored)
condition_type(restored)

## ----python-envelope----------------------------------------------------------
fixture <- system.file(
  "schema", "fixtures", "ordinary-exception.json",
  package = "dataexcept"
)
stopifnot(nzchar(fixture))

python_payload <- paste(readLines(fixture, warn = FALSE), collapse = "\n")
python_error <- envelope_to_condition(python_payload)
stopifnot(inherits(python_error, "dataexcept_validation_error"))
condition_type(python_error)
condition_failure(python_error)$kind

## ----observability------------------------------------------------------------
context <- operation_context(
  system = "batch",
  component = "orders",
  operation = "validate_orders",
  job_id = "job-42"
)
cat(condition_to_event_json(caught, operation_context = context))

