macro_rules! error {
($error_type:expr, $error:expr $(, $key:literal = $value:expr)* $(,)?) => { ... };
}Expand description
Records an error event on the current span and returns an error value.
This macro adds an error event to the current OpenTelemetry span following the semantic conventions, then evaluates to the provided error value.
§Syntax
ⓘ
// In closures (ok_or_else, map_err, etc.)
.ok_or_else(|| otel::error!("timeout", Error::new("msg")))?
// In function bodies with explicit return
return Err(otel::error!("validation_failed", Error::new("msg")));
// With additional attributes
otel::error!("database_unavailable", error, "retry_count" = 3)§Parameters
error_type: String literal for the error.type attributeerror_value: The error value to return (must implement Display for error.message)- Additional key-value pairs: Optional extra attributes to add to the error event
§Examples
ⓘ
// In ok_or_else closure
let config = load_config().ok_or_else(|| {
otel::error!("config_not_found",
jsonrpc::Error::internal_error("Configuration file not found"))
})?;
// In map_err closure
let connection = establish_connection().map_err(|e| {
otel::error!("connection_failed",
jsonrpc::Error::internal_error(format!("Failed to connect: {}", e)),
"host" = host.to_string(),
"port" = port as i64
)
})?;
// Direct return
if !is_valid {
return Err(otel::error!("invalid_state",
jsonrpc::Error::internal_error("System is in an invalid state"),
"state" = current_state
));
}§OpenTelemetry Semantic Conventions
The macro follows the OpenTelemetry semantic conventions for errors:
- Event name:
"error" - Required attributes:
error.type: Describes the class of error the operation ended witherror.message: A human-readable message providing more detail about the error
- Additional attributes: Any extra key-value pairs provided
§Difference from exception!
While both macros record error-related events, they follow different semantic conventions:
error!: For general error conditions (useserror.typeanderror.message)exception!: For programming exceptions with stack traces (usesexception.typeandexception.message)
Use error! for application-level errors and exception! for exception handling.