Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(flags): collapse wrapper FlagError variants into anyhow buckets (#84644)

James Gill46779bf2e0a8
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index 47f612351e8d..5fe0c508bdee 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -230,7 +230,8 @@ async fn scan_persons_page(
.await
.map_err(|e| {
warn!(team_id, cursor, "Batch eval person scan failed: {e}");
- FlagError::Internal(format!("person scan query failed: {e}"))
+ let message = format!("person scan query failed: {e}");
+ FlagError::internal(anyhow::Error::new(e).context(message))
})
}
diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rs
index 6c6adb485ec7..93d598915b68 100644
--- a/rust/feature-flags/src/api/errors.rs
+++ b/rust/feature-flags/src/api/errors.rs
@@ -56,8 +56,19 @@ pub enum ClientFacingError {
pub enum FlagError {
#[error(transparent)]
ClientFacing(#[from] ClientFacingError),
- #[error("Internal error: {0}")]
- Internal(String),
+ /// `code` is public: it ships as `reason.code` and as a metrics label.
+ /// Named `cause` because thiserror would treat `source` as `#[source]`,
+ /// which `anyhow::Error` cannot satisfy.
+ #[error("{cause}")]
+ InternalError {
+ code: &'static str,
+ cause: anyhow::Error,
+ },
+ #[error("{cause}")]
+ Unavailable {
+ code: &'static str,
+ cause: anyhow::Error,
+ },
#[error("failed to decode request: {0}")]
RequestDecodingError(String),
#[error("Decompressed request body exceeds limit ({decompressed} > {limit} bytes)")]
@@ -80,13 +91,6 @@ pub enum FlagError {
NoAuthenticationProvided,
#[error("Row not found in postgres")]
RowNotFound,
- /// Data parsing error with context about what failed.
- /// This is an internal error (500) indicating data corruption or schema mismatch,
- /// not a service availability issue.
- #[error("Failed to parse flag data: {0}")]
- DataParsingErrorWithContext(String),
- #[error("redis unavailable")]
- RedisUnavailable,
#[error("database unavailable")]
DatabaseUnavailable,
#[error("Failed to fetch hash key override for experience continuity")]
@@ -115,14 +119,6 @@ pub enum FlagError {
CohortFiltersParsingError,
#[error("Dependency cycle detected: {0} id {1} starts the cycle")]
DependencyCycle(DependencyType, i64),
- #[error("Person not found")]
- PersonNotFound,
- #[error("Cache miss - data not found in cache")]
- CacheMiss,
- #[error("Failed to parse data")]
- DataParsingError,
- #[error("Parallel batch evaluation task panicked")]
- BatchEvaluationPanicked,
#[error("Rayon semaphore acquisition timed out after {0}ms")]
RayonSemaphoreTimeout(u64),
#[error(transparent)]
@@ -134,7 +130,67 @@ pub enum FlagError {
RemoteConfigDecryptFailed(String),
}
+/// Codes that `IntoResponse` branches on, so the constructor and the arm cannot
+/// drift apart. The codes used at one site only stay inline: a single literal has
+/// no second reference to disagree with.
+pub(crate) const CODE_FLAG_DATA_PARSING: &str = "flag_data_parsing_error";
+pub(crate) const CODE_PERSON_NOT_FOUND: &str = "person_not_found";
+
impl FlagError {
+ /// The `Internal error: ` prefix reaches customers as the `$feature_flag_reason`
+ /// event property, so changing it changes their data. `context` keeps the chain.
+ pub fn internal(cause: impl Into<anyhow::Error>) -> Self {
+ let cause = cause.into();
+ let message = format!("Internal error: {cause}");
+ FlagError::InternalError {
+ code: "internal_error",
+ cause: cause.context(message),
+ }
+ }
+
+ /// Corrupt or mismatched data, so a 500 rather than a retryable 503.
+ pub fn flag_data_parsing(details: impl std::fmt::Display) -> Self {
+ FlagError::InternalError {
+ code: CODE_FLAG_DATA_PARSING,
+ cause: anyhow::anyhow!("Failed to parse flag data: {details}"),
+ }
+ }
+
+ pub fn data_parsing(cause: impl Into<anyhow::Error>) -> Self {
+ FlagError::InternalError {
+ code: "data_parsing_error",
+ cause: cause.into().context("Failed to parse data"),
+ }
+ }
+
+ pub fn batch_evaluation_panicked() -> Self {
+ FlagError::InternalError {
+ code: "batch_evaluation_panicked",
+ cause: anyhow::anyhow!("Parallel batch evaluation task panicked"),
+ }
+ }
+
+ pub fn redis_unavailable(cause: impl Into<anyhow::Error>) -> Self {
+ FlagError::Unavailable {
+ code: "redis_unavailable",
+ cause: cause.into().context("redis unavailable"),
+ }
+ }
+
+ pub fn cache_miss() -> Self {
+ FlagError::Unavailable {
+ code: "cache_miss",
+ cause: anyhow::anyhow!("Cache miss - data not found in cache"),
+ }
+ }
+
+ pub fn person_not_found() -> Self {
+ FlagError::Unavailable {
+ code: CODE_PERSON_NOT_FOUND,
+ cause: anyhow::anyhow!("Person not found"),
+ }
+ }
+
/// Returns (error_code, status_code) for this error.
///
/// This consolidates error classification in one place to ensure consistency
@@ -171,29 +227,23 @@ impl FlagError {
FlagError::SecretApiTokenInvalid => ("secret_api_token_invalid", 401),
FlagError::NoAuthenticationProvided => ("no_authentication", 401),
+ // Bucketed errors carry their own stable code.
+ FlagError::InternalError { code, .. } => (code, 500),
+ FlagError::Unavailable { code, .. } => (code, 503),
+
// Internal server errors (500)
- FlagError::Internal(_) => ("internal_error", 500),
FlagError::DatabaseError(_, _) => ("database_error", 500),
FlagError::RowNotFound => ("row_not_found", 500),
FlagError::DependencyNotFound(_, _) => ("dependency_not_found", 500),
FlagError::CohortFiltersParsingError => ("cohort_filters_parsing_error", 500),
FlagError::DependencyCycle(_, _) => ("dependency_cycle", 500),
- FlagError::DataParsingError => ("data_parsing_error", 500),
- FlagError::BatchEvaluationPanicked => ("batch_evaluation_panicked", 500),
FlagError::HashKeyOverrideError => ("hash_key_override_error", 500),
FlagError::RayonSemaphoreTimeout(_) => ("rayon_semaphore_timeout", 504),
FlagError::RemoteConfigDecryptFailed(_) => ("remote_config_decrypt_failed", 500),
- // Data parsing errors (500) - internal errors, not service unavailability
- FlagError::DataParsingErrorWithContext(_) => ("flag_data_parsing_error", 500),
-
// Service unavailable errors (503) - transient issues, retry may help
- FlagError::RedisUnavailable => ("redis_unavailable", 503),
FlagError::DatabaseUnavailable => ("database_unavailable", 503),
FlagError::TimeoutError(_) => ("timeout", 503),
- FlagError::CacheMiss => ("cache_miss", 503),
- // Cache misses for person/cohort data - transient, data may be populated soon
- FlagError::PersonNotFound => ("person_not_found", 503),
// Cookieless errors (mixed)
FlagError::CookielessError(err) => match err {
@@ -341,11 +391,33 @@ impl IntoResponse for FlagError {
}
ClientFacingError::ServiceUnavailable => (StatusCode::SERVICE_UNAVAILABLE, "Service is currently unavailable. Please try again later.".to_string()),
},
- FlagError::Internal(msg) => {
- tracing::error!("Internal server error: {}", msg);
+ FlagError::InternalError { code, cause } => {
+ tracing::error!(error_code = code, "Internal server error: {cause:?}");
+ // Corrupt flag data will fail every retry, so this one names the
+ // thing the customer can actually fix.
+ let detail = if code == CODE_FLAG_DATA_PARSING {
+ "Failed to parse flag configuration data. This may indicate a misconfigured feature flag. Please check your flag definitions or contact support."
+ } else {
+ "An internal server error occurred. Please try again later or contact support if the problem persists."
+ };
+ (StatusCode::INTERNAL_SERVER_ERROR, detail.to_string())
+ }
+ FlagError::Unavailable { code, cause } => {
+ match code {
+ // A person row that has not landed yet is expected under
+ // replication lag, so it does not deserve an error line.
+ CODE_PERSON_NOT_FOUND => tracing::warn!(
+ error_code = code,
+ "Service dependency unavailable: {cause:?}"
+ ),
+ _ => tracing::error!(
+ error_code = code,
+ "Service dependency unavailable: {cause:?}"
+ ),
+ }
(
- StatusCode::INTERNAL_SERVER_ERROR,
- "An internal server error occurred. Please try again later or contact support if the problem persists.".to_string(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "A service dependency is temporarily unavailable. This is likely a temporary issue. Please try again later.".to_string(),
)
}
FlagError::RequestDecodingError(msg) => {
@@ -421,20 +493,6 @@ impl IntoResponse for FlagError {
};
return (StatusCode::UNAUTHORIZED, Json(response)).into_response();
}
- FlagError::DataParsingErrorWithContext(ref details) => {
- tracing::error!("Data parsing error: {}", details);
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "Failed to parse flag configuration data. This may indicate a misconfigured feature flag. Please check your flag definitions or contact support.".to_string(),
- )
- }
- FlagError::RedisUnavailable => {
- tracing::error!("Redis unavailable: {:?}", self);
- (
- StatusCode::SERVICE_UNAVAILABLE,
- "Our cache service is currently unavailable. This is likely a temporary issue. Please try again later.".to_string(),
- )
- }
FlagError::DatabaseUnavailable => {
tracing::error!("Database unavailable: {:?}", self);
(
@@ -484,22 +542,6 @@ impl IntoResponse for FlagError {
tracing::error!("Failed to fetch hash key override for experience continuity");
(StatusCode::INTERNAL_SERVER_ERROR, "Failed to fetch hash key override for experience continuity. Please try again later.".to_string())
}
- FlagError::PersonNotFound => {
- tracing::warn!("Person not found in cache");
- (StatusCode::SERVICE_UNAVAILABLE, "Person data not yet available. This is a temporary issue while data is being populated. Please try again.".to_string())
- }
- FlagError::CacheMiss => {
- tracing::error!("Cache miss - required data not found in cache");
- (StatusCode::SERVICE_UNAVAILABLE, "Required data not found in cache. This is likely a temporary issue. Please try again later.".to_string())
- }
- FlagError::DataParsingError => {
- tracing::error!("Failed to parse data");
- (StatusCode::INTERNAL_SERVER_ERROR, "Failed to parse internal data. This is likely a temporary issue. Please try again later.".to_string())
- }
- FlagError::BatchEvaluationPanicked => {
- tracing::error!("Parallel batch evaluation task panicked");
- (StatusCode::INTERNAL_SERVER_ERROR, "An internal error occurred during flag evaluation. Please try again later.".to_string())
- }
FlagError::RayonSemaphoreTimeout(ms) => {
tracing::warn!("Rayon semaphore acquisition timed out after {}ms", ms);
(StatusCode::GATEWAY_TIMEOUT, format!("Evaluation pool busy, timed out after {ms}ms. Please retry."))
@@ -575,15 +617,13 @@ impl From<CustomRedisError> for FlagError {
fn from(e: CustomRedisError) -> Self {
match e {
CustomRedisError::NotFound => FlagError::TokenValidationError,
- CustomRedisError::ParseError(details) => {
- FlagError::DataParsingErrorWithContext(format!(
- "Redis data parsing failed: {}",
- simplify_serde_error(&details)
- ))
- }
+ CustomRedisError::ParseError(details) => FlagError::flag_data_parsing(format!(
+ "Redis data parsing failed: {}",
+ simplify_serde_error(&details)
+ )),
CustomRedisError::Timeout => FlagError::TimeoutError(Some("Redis timeout".to_string())),
- CustomRedisError::InvalidConfiguration(_) | CustomRedisError::Redis(_) => {
- FlagError::RedisUnavailable
+ e @ (CustomRedisError::InvalidConfiguration(_) | CustomRedisError::Redis(_)) => {
+ FlagError::redis_unavailable(e)
}
}
}
@@ -643,10 +683,12 @@ impl From<sqlx::Error> for FlagError {
impl From<HyperCacheError> for FlagError {
fn from(e: HyperCacheError) -> Self {
match e {
- HyperCacheError::CacheMiss => FlagError::CacheMiss,
+ HyperCacheError::CacheMiss => FlagError::cache_miss(),
HyperCacheError::Redis(redis_error) => FlagError::from(redis_error),
- HyperCacheError::S3(_) => FlagError::CacheMiss,
- HyperCacheError::Json(_) | HyperCacheError::Pickle(_) => FlagError::DataParsingError,
+ HyperCacheError::S3(_) => FlagError::cache_miss(),
+ e @ (HyperCacheError::Json(_) | HyperCacheError::Pickle(_)) => {
+ FlagError::data_parsing(e)
+ }
HyperCacheError::Timeout(_) => {
FlagError::TimeoutError(Some("cache_timeout".to_string()))
}
@@ -657,16 +699,45 @@ impl From<HyperCacheError> for FlagError {
#[cfg(test)]
mod tests {
use super::*;
+ use rstest::rstest;
use tokio::time::{timeout, Duration};
+ /// These strings reach customers as the `$feature_flag_reason` event property.
+ #[rstest]
+ #[case(FlagError::internal(anyhow::anyhow!("boom")), "Internal error: boom")]
+ #[case(
+ FlagError::flag_data_parsing("bad json"),
+ "Failed to parse flag data: bad json"
+ )]
+ #[case(
+ FlagError::data_parsing(anyhow::anyhow!("bad payload")),
+ "Failed to parse data"
+ )]
+ #[case(
+ FlagError::batch_evaluation_panicked(),
+ "Parallel batch evaluation task panicked"
+ )]
+ #[case(
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")),
+ "redis unavailable"
+ )]
+ #[case(FlagError::cache_miss(), "Cache miss - data not found in cache")]
+ #[case(FlagError::person_not_found(), "Person not found")]
+ fn test_bucketed_error_descriptions_are_stable(
+ #[case] error: FlagError,
+ #[case] expected: &str,
+ ) {
+ assert_eq!(error.evaluation_error_description(), expected);
+ }
+
#[test]
fn test_is_5xx() {
// Test 5XX errors
- assert!(FlagError::Internal("test".to_string()).is_5xx());
+ assert!(FlagError::internal(anyhow::anyhow!("test")).is_5xx());
assert!(FlagError::DatabaseUnavailable.is_5xx());
- assert!(FlagError::RedisUnavailable.is_5xx());
+ assert!(FlagError::redis_unavailable(anyhow::anyhow!("connection refused")).is_5xx());
assert!(FlagError::TimeoutError(None).is_5xx());
- assert!(FlagError::BatchEvaluationPanicked.is_5xx());
+ assert!(FlagError::batch_evaluation_panicked().is_5xx());
assert!(FlagError::RayonSemaphoreTimeout(800).is_5xx());
assert!(FlagError::ClientFacing(ClientFacingError::ServiceUnavailable).is_5xx());
@@ -725,6 +796,113 @@ mod tests {
);
}
+ fn response_body(error: FlagError) -> (StatusCode, String) {
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let response = error.into_response();
+ let status = response.status();
+ let bytes = rt
+ .block_on(axum::body::to_bytes(response.into_body(), usize::MAX))
+ .unwrap();
+ (status, String::from_utf8(bytes.to_vec()).unwrap())
+ }
+
+ /// Every bucketed code renders one of three bodies. A corrupt flag definition
+ /// fails each retry, so it gets guidance the other two cannot give; the rest
+ /// share a body, which is the wording that replaced their per-variant text.
+ #[rstest]
+ #[case(
+ FlagError::flag_data_parsing("bad json"),
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "check your flag definitions"
+ )]
+ #[case(
+ FlagError::data_parsing(anyhow::anyhow!("bad payload")),
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "An internal server error occurred"
+ )]
+ #[case(
+ FlagError::batch_evaluation_panicked(),
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "An internal server error occurred"
+ )]
+ #[case(
+ FlagError::internal(anyhow::anyhow!("boom")),
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "An internal server error occurred"
+ )]
+ #[case(
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "A service dependency is temporarily unavailable"
+ )]
+ #[case(
+ FlagError::cache_miss(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "A service dependency is temporarily unavailable"
+ )]
+ #[case(
+ FlagError::person_not_found(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "A service dependency is temporarily unavailable"
+ )]
+ fn test_bucketed_response_bodies(
+ #[case] error: FlagError,
+ #[case] expected_status: StatusCode,
+ #[case] expected_body: &str,
+ ) {
+ let (status, body) = response_body(error);
+ assert_eq!(status, expected_status);
+ assert!(
+ body.contains(expected_body),
+ "expected body to contain {expected_body:?}, got: {body}"
+ );
+ }
+
+ /// `IntoResponse` picks the log level by comparing `code`, which the compiler
+ /// cannot check. A drift here would silently bury a Redis outage at warn.
+ #[rstest]
+ #[case(FlagError::redis_unavailable(anyhow::anyhow!("refused")), "ERROR")]
+ #[case(FlagError::cache_miss(), "ERROR")]
+ #[case(FlagError::person_not_found(), "WARN")]
+ #[case(FlagError::internal(anyhow::anyhow!("boom")), "ERROR")]
+ fn test_bucketed_log_levels(#[case] error: FlagError, #[case] expected_level: &str) {
+ #[derive(Clone, Default)]
+ struct Capture(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
+
+ impl std::io::Write for Capture {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
+ type Writer = Self;
+ fn make_writer(&'a self) -> Self::Writer {
+ self.clone()
+ }
+ }
+
+ let writer = Capture::default();
+ let subscriber = tracing_subscriber::fmt()
+ .json()
+ .with_writer(writer.clone())
+ .with_max_level(tracing::Level::INFO)
+ .finish();
+ tracing::subscriber::with_default(subscriber, || {
+ drop(error.into_response());
+ });
+
+ let logs = String::from_utf8(writer.0.lock().unwrap().clone()).unwrap();
+ assert!(
+ logs.contains(&format!("\"level\":\"{expected_level}\"")),
+ "expected a {expected_level} line, got: {logs}"
+ );
+ }
+
#[test]
fn test_remote_config_decrypt_failed_response_is_json() {
// The remote_config response body must be JSON on every status code, because SDKs call
@@ -859,7 +1037,7 @@ mod tests {
FlagError::ClientFacing(ClientFacingError::TokenRateLimited),
FlagError::ClientFacing(ClientFacingError::BillingLimit),
FlagError::ClientFacing(ClientFacingError::ServiceUnavailable),
- FlagError::Internal("test".to_string()),
+ FlagError::internal(anyhow::anyhow!("test")),
FlagError::RequestDecodingError("test".to_string()),
serde_json::from_str::<String>("invalid json")
.unwrap_err()
@@ -876,18 +1054,18 @@ mod tests {
FlagError::SecretApiTokenInvalid,
FlagError::NoAuthenticationProvided,
FlagError::RowNotFound,
- FlagError::DataParsingErrorWithContext("test parse error".to_string()),
- FlagError::RedisUnavailable,
+ FlagError::flag_data_parsing("test parse error"),
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")),
FlagError::DatabaseUnavailable,
FlagError::DatabaseError(sqlx::Error::RowNotFound, Some("test context".to_string())),
FlagError::TimeoutError(None),
FlagError::DependencyNotFound(DependencyType::Flag, 1),
FlagError::DependencyCycle(DependencyType::Cohort, 2),
FlagError::CohortFiltersParsingError,
- FlagError::PersonNotFound,
- FlagError::CacheMiss,
- FlagError::DataParsingError,
- FlagError::BatchEvaluationPanicked,
+ FlagError::person_not_found(),
+ FlagError::cache_miss(),
+ FlagError::data_parsing(anyhow::anyhow!("bad payload")),
+ FlagError::batch_evaluation_panicked(),
FlagError::HashKeyOverrideError,
FlagError::RayonSemaphoreTimeout(800),
CookielessManagerError::MissingProperty("test".to_string()).into(), // CookielessError
@@ -938,9 +1116,12 @@ mod tests {
);
// 5xx errors (server errors)
- assert_eq!(FlagError::Internal("".into()).status_code(), 500);
+ assert_eq!(FlagError::internal(anyhow::anyhow!("")).status_code(), 500);
assert_eq!(FlagError::DatabaseUnavailable.status_code(), 503);
- assert_eq!(FlagError::RedisUnavailable.status_code(), 503);
+ assert_eq!(
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")).status_code(),
+ 503
+ );
assert_eq!(FlagError::TimeoutError(None).status_code(), 503);
assert_eq!(
FlagError::ClientFacing(ClientFacingError::ServiceUnavailable).status_code(),
@@ -948,7 +1129,7 @@ mod tests {
);
assert_eq!(FlagError::RowNotFound.status_code(), 500);
// Cache miss errors are now 503 (transient)
- assert_eq!(FlagError::PersonNotFound.status_code(), 503);
+ assert_eq!(FlagError::person_not_found().status_code(), 503);
// Semaphore timeout is 504 (gateway timeout for ingress retry)
assert_eq!(FlagError::RayonSemaphoreTimeout(800).status_code(), 504);
}
@@ -972,10 +1153,10 @@ mod tests {
// Server errors should be 5xx
let server_errors = vec![
- FlagError::Internal("".into()),
+ FlagError::internal(anyhow::anyhow!("")),
FlagError::RowNotFound,
FlagError::CohortFiltersParsingError,
- FlagError::DataParsingError,
+ FlagError::data_parsing(anyhow::anyhow!("bad payload")),
];
for error in server_errors {
let status = error.status_code();
@@ -987,22 +1168,22 @@ mod tests {
fn test_error_code_consistency_with_is_5xx() {
// Verify that status_code() >= 500 matches is_5xx() for ALL 5xx errors
let errors_5xx = vec![
- FlagError::Internal("test".to_string()),
+ FlagError::internal(anyhow::anyhow!("test")),
FlagError::DatabaseError(sqlx::Error::RowNotFound, None),
FlagError::RowNotFound,
FlagError::DependencyNotFound(DependencyType::Flag, 1),
FlagError::CohortFiltersParsingError,
FlagError::DependencyCycle(DependencyType::Cohort, 2),
- FlagError::DataParsingError,
- FlagError::BatchEvaluationPanicked,
+ FlagError::data_parsing(anyhow::anyhow!("bad payload")),
+ FlagError::batch_evaluation_panicked(),
FlagError::HashKeyOverrideError,
FlagError::RayonSemaphoreTimeout(800),
- FlagError::DataParsingErrorWithContext("test".to_string()),
- FlagError::RedisUnavailable,
+ FlagError::flag_data_parsing("test"),
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")),
FlagError::DatabaseUnavailable,
FlagError::TimeoutError(None),
- FlagError::CacheMiss,
- FlagError::PersonNotFound,
+ FlagError::cache_miss(),
+ FlagError::person_not_found(),
FlagError::ClientFacing(ClientFacingError::ServiceUnavailable),
];
@@ -1027,14 +1208,17 @@ mod tests {
assert!(FlagError::RowNotFound.is_token_not_found());
// Transient infrastructure errors should NOT be treated as "not found"
- assert!(!FlagError::CacheMiss.is_token_not_found());
- assert!(!FlagError::RedisUnavailable.is_token_not_found());
+ assert!(!FlagError::cache_miss().is_token_not_found());
+ assert!(
+ !FlagError::redis_unavailable(anyhow::anyhow!("connection refused"))
+ .is_token_not_found()
+ );
assert!(!FlagError::DatabaseUnavailable.is_token_not_found());
assert!(!FlagError::TimeoutError(None).is_token_not_found());
assert!(!FlagError::TimeoutError(Some("pool_timeout".to_string())).is_token_not_found());
assert!(!FlagError::DatabaseError(sqlx::Error::PoolTimedOut, None).is_token_not_found());
- assert!(!FlagError::Internal("serialization failed".to_string()).is_token_not_found());
- assert!(!FlagError::DataParsingError.is_token_not_found());
+ assert!(!FlagError::internal(anyhow::anyhow!("serialization failed")).is_token_not_found());
+ assert!(!FlagError::data_parsing(anyhow::anyhow!("bad payload")).is_token_not_found());
}
#[test]
@@ -1062,7 +1246,7 @@ mod tests {
"database_unavailable"
);
assert_eq!(
- FlagError::RedisUnavailable.error_code(),
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")).error_code(),
"redis_unavailable"
);
}
@@ -1080,7 +1264,7 @@ mod tests {
FlagError::ClientFacing(ClientFacingError::TokenRateLimited),
FlagError::ClientFacing(ClientFacingError::BillingLimit),
FlagError::ClientFacing(ClientFacingError::ServiceUnavailable),
- FlagError::Internal("test".to_string()),
+ FlagError::internal(anyhow::anyhow!("test")),
FlagError::RequestDecodingError("test".to_string()),
serde_json::from_str::<String>("invalid json")
.unwrap_err()
@@ -1097,18 +1281,18 @@ mod tests {
FlagError::SecretApiTokenInvalid,
FlagError::NoAuthenticationProvided,
FlagError::RowNotFound,
- FlagError::DataParsingErrorWithContext("test parse error".to_string()),
- FlagError::RedisUnavailable,
+ FlagError::flag_data_parsing("test parse error"),
+ FlagError::redis_unavailable(anyhow::anyhow!("connection refused")),
FlagError::DatabaseUnavailable,
FlagError::DatabaseError(sqlx::Error::RowNotFound, Some("test context".to_string())),
FlagError::TimeoutError(None),
FlagError::DependencyNotFound(DependencyType::Flag, 1),
FlagError::DependencyCycle(DependencyType::Cohort, 2),
FlagError::CohortFiltersParsingError,
- FlagError::PersonNotFound,
- FlagError::CacheMiss,
- FlagError::DataParsingError,
- FlagError::BatchEvaluationPanicked,
+ FlagError::person_not_found(),
+ FlagError::cache_miss(),
+ FlagError::data_parsing(anyhow::anyhow!("bad payload")),
+ FlagError::batch_evaluation_panicked(),
FlagError::HashKeyOverrideError,
FlagError::RayonSemaphoreTimeout(800),
CookielessManagerError::MissingProperty("test".to_string()).into(),
diff --git a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
index 16c8c1e53fec..a1146b43b353 100644
--- a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
+++ b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
@@ -236,7 +236,7 @@ impl From<CohortFetchError> for FlagError {
fn from(value: CohortFetchError) -> Self {
match value {
CohortFetchError::DatabaseUnavailable => FlagError::DatabaseUnavailable,
- CohortFetchError::QueryFailed(msg) => FlagError::Internal(msg),
+ CohortFetchError::QueryFailed(msg) => FlagError::internal(anyhow::anyhow!(msg)),
}
}
}
@@ -1225,12 +1225,15 @@ mod tests {
"DatabaseUnavailable should map to FlagError::DatabaseUnavailable"
);
- // QueryFailed -> FlagError::Internal
let query_failed = CohortFetchError::QueryFailed("test error".to_string());
let flag_error: FlagError = query_failed.into();
assert!(
- matches!(flag_error, FlagError::Internal(msg) if msg == "test error"),
- "QueryFailed should map to FlagError::Internal with the message"
+ matches!(flag_error, FlagError::InternalError { ref cause, .. } if cause.to_string() == "Internal error: test error"),
+ "QueryFailed should render as `Internal error: <message>`"
+ );
+ assert_eq!(
+ flag_error.evaluation_error_description(),
+ "Internal error: test error"
);
}
}
diff --git a/rust/feature-flags/src/database_pools.rs b/rust/feature-flags/src/database_pools.rs
index 528bada579ba..ef56dd11a311 100644
--- a/rust/feature-flags/src/database_pools.rs
+++ b/rust/feature-flags/src/database_pools.rs
@@ -45,9 +45,9 @@ impl DatabasePools {
pub async fn from_config(config: &Config) -> Result<Self, FlagError> {
// Validate acquire_timeout_secs - must be at least 1 second
if config.acquire_timeout_secs == 0 {
- return Err(FlagError::Internal(
- "ACQUIRE_TIMEOUT_SECS must be at least 1 second".to_string(),
- ));
+ return Err(FlagError::internal(anyhow::anyhow!(
+ "ACQUIRE_TIMEOUT_SECS must be at least 1 second"
+ )));
}
// Validate and fix max_connections if it's 0
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index 4c860796e298..1f88d6d7edcc 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -110,7 +110,7 @@ impl FeatureFlagList {
wrapper.flags.len(),
team_id
);
- return Err(FlagError::DataParsingErrorWithContext(format!(
+ return Err(FlagError::flag_data_parsing(format!(
"evaluation_metadata.dependency_stages is empty but {} flags present for team {team_id}",
wrapper.flags.len()
)));
@@ -181,7 +181,8 @@ impl FeatureFlagList {
team_id,
e
);
- FlagError::Internal(format!("Database query error: {e}"))
+ let message = format!("Database query error: {e}");
+ FlagError::internal(anyhow::Error::new(e).context(message))
})?;
let flags: Vec<FeatureFlag> = flags_row
@@ -1112,7 +1113,10 @@ mod tests {
let result = FeatureFlagList::from_wrapper(Some(wrapper), 1);
assert!(matches!(
result,
- Err(FlagError::DataParsingErrorWithContext(_))
+ Err(FlagError::InternalError {
+ code: "flag_data_parsing_error",
+ ..
+ })
));
}
diff --git a/rust/feature-flags/src/flags/flag_definitions_cache.rs b/rust/feature-flags/src/flags/flag_definitions_cache.rs
index 449171c93cb0..826751809acc 100644
--- a/rust/feature-flags/src/flags/flag_definitions_cache.rs
+++ b/rust/feature-flags/src/flags/flag_definitions_cache.rs
@@ -252,7 +252,7 @@ impl FlagDefinitionsCache {
/// Validates a `HypercacheFlagsWrapper` and compiles its regexes. Validation
/// runs here, not on the cache-lookup path, so hits never re-validate.
-/// Malformed wrappers fail fast with `DataParsingErrorWithContext`.
+/// Malformed wrappers fail fast with the `flag_data_parsing_error` 500.
pub(crate) fn compile_from_wrapper(
team_id: TeamId,
wrapper: Option<HypercacheFlagsWrapper>,
@@ -636,8 +636,8 @@ mod tests {
}
/// A malformed wrapper (flags present but `dependency_stages` empty) must
- /// surface as `FlagError::DataParsingErrorWithContext`, not be collapsed
- /// into `Internal` at the cache boundary.
+ /// surface under the `flag_data_parsing_error` code, not be collapsed into a
+ /// generic `internal_error` at the cache boundary.
#[tokio::test]
async fn test_validation_errors_preserve_variant() {
let cache = FlagDefinitionsCache::new(None, None);
@@ -656,8 +656,14 @@ mod tests {
.await
.expect_err("malformed wrapper must error");
assert!(
- matches!(err, FlagError::DataParsingErrorWithContext(_)),
- "expected DataParsingErrorWithContext, got {err:?}"
+ matches!(
+ err,
+ FlagError::InternalError {
+ code: "flag_data_parsing_error",
+ ..
+ }
+ ),
+ "expected flag_data_parsing_error, got {err:?}"
);
}
diff --git a/rust/feature-flags/src/flags/flag_group_type_mapping.rs b/rust/feature-flags/src/flags/flag_group_type_mapping.rs
index fbd935ad1507..c0ba63cb28a6 100644
--- a/rust/feature-flags/src/flags/flag_group_type_mapping.rs
+++ b/rust/feature-flags/src/flags/flag_group_type_mapping.rs
@@ -77,7 +77,7 @@ impl From<GroupTypeFetchError> for FlagError {
fn from(value: GroupTypeFetchError) -> Self {
match value {
GroupTypeFetchError::DatabaseUnavailable => FlagError::DatabaseUnavailable,
- GroupTypeFetchError::QueryFailed(msg) => FlagError::Internal(msg),
+ GroupTypeFetchError::QueryFailed(msg) => FlagError::internal(anyhow::anyhow!(msg)),
}
}
}
@@ -527,7 +527,9 @@ mod tests {
let query_failed = GroupTypeFetchError::QueryFailed("test error".to_string());
let flag_error: FlagError = query_failed.into();
- assert!(matches!(flag_error, FlagError::Internal(msg) if msg == "test error"));
+ assert!(
+ matches!(flag_error, FlagError::InternalError { ref cause, .. } if cause.to_string() == "Internal error: test error")
+ );
}
#[test]
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index eb4e6452c8b7..fe87d2d17d7e 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -1276,7 +1276,7 @@ impl FeatureFlagMatcher {
evaluation_tags: None,
bucketing_identifier: None,
};
- (stub, Err(FlagError::BatchEvaluationPanicked))
+ (stub, Err(FlagError::batch_evaluation_panicked()))
})
.collect()
}
@@ -2301,7 +2301,7 @@ impl FeatureFlagMatcher {
tracing::debug!(
"Person properties not in cache — DB prep was skipped (overrides cover all needed keys)"
);
- Err(FlagError::PersonNotFound)
+ Err(FlagError::person_not_found())
}
PersonPropertyState::Pending => {
inc(
@@ -2317,7 +2317,7 @@ impl FeatureFlagMatcher {
log.eval.person_properties_not_cached = true;
});
tracing::error!("Person properties not found — DB prep never ran");
- Err(FlagError::PersonNotFound)
+ Err(FlagError::person_not_found())
}
}
}
@@ -2560,19 +2560,37 @@ mod tests {
assert_eq!(stub_a.key, "flag_a");
assert_eq!(stub_a.id, 10);
assert_eq!(stub_a.version, Some(3));
- assert!(matches!(err_a, Err(FlagError::BatchEvaluationPanicked)));
+ assert!(matches!(
+ err_a,
+ Err(FlagError::InternalError {
+ code: "batch_evaluation_panicked",
+ ..
+ })
+ ));
let (stub_b, err_b) = &results[1];
assert_eq!(stub_b.key, "flag_b");
assert_eq!(stub_b.id, 20);
assert_eq!(stub_b.version, None);
- assert!(matches!(err_b, Err(FlagError::BatchEvaluationPanicked)));
+ assert!(matches!(
+ err_b,
+ Err(FlagError::InternalError {
+ code: "batch_evaluation_panicked",
+ ..
+ })
+ ));
let (stub_c, err_c) = &results[2];
assert_eq!(stub_c.key, "flag_c");
assert_eq!(stub_c.id, 30);
assert_eq!(stub_c.version, Some(1));
- assert!(matches!(err_c, Err(FlagError::BatchEvaluationPanicked)));
+ assert!(matches!(
+ err_c,
+ Err(FlagError::InternalError {
+ code: "batch_evaluation_panicked",
+ ..
+ })
+ ));
for (stub, _) in &results {
assert_eq!(stub.team_id, team_id);
diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rs
index 7dd15a6979ff..4763d6bc472d 100644
--- a/rust/feature-flags/src/flags/flag_operations.rs
+++ b/rust/feature-flags/src/flags/flag_operations.rs
@@ -719,7 +719,10 @@ mod tests {
let result = get_flags_from_redis(redis_client, team.id).await;
assert!(matches!(
result,
- Err(FlagError::DataParsingErrorWithContext(_))
+ Err(FlagError::InternalError {
+ code: "flag_data_parsing_error",
+ ..
+ })
));
// Test database query error (using a non-existent table)
diff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rs
index c4416b4ef21f..ff166dd41277 100644
--- a/rust/feature-flags/src/flags/flag_service.rs
+++ b/rust/feature-flags/src/flags/flag_service.rs
@@ -258,7 +258,7 @@ impl FlagService {
"component" => "flag_service",
)
.increment(1);
- Err(FlagError::DataParsingErrorWithContext(format!(
+ Err(FlagError::flag_data_parsing(format!(
"Failed to parse feature flags for team {team_id}: {e}"
)))
}
@@ -932,7 +932,7 @@ mod tests {
);
}
- /// Corrupt Redis payload must hard-fail with DataParsingErrorWithContext rather
+ /// Corrupt Redis payload must hard-fail under `flag_data_parsing_error` rather
/// than silently fall back to PG (which would serve single-stage data).
#[tokio::test]
async fn test_get_flags_hard_fails_on_hypercache_parse_error() {
@@ -969,7 +969,13 @@ mod tests {
let result = flag_service.get_flags_from_cache_or_pg(team.id).await;
assert!(
- matches!(result, Err(FlagError::DataParsingErrorWithContext(_))),
+ matches!(
+ result,
+ Err(FlagError::InternalError {
+ code: "flag_data_parsing_error",
+ ..
+ })
+ ),
"parse error must hard-fail, got {result:?}"
);
}
@@ -1009,7 +1015,13 @@ mod tests {
let result = flag_service.get_flags_from_cache_or_pg(team.id).await;
assert!(
- matches!(result, Err(FlagError::DataParsingErrorWithContext(_))),
+ matches!(
+ result,
+ Err(FlagError::InternalError {
+ code: "flag_data_parsing_error",
+ ..
+ })
+ ),
"pickle error must hard-fail, got {result:?}"
);
}
diff --git a/rust/feature-flags/src/flags/test_helpers.rs b/rust/feature-flags/src/flags/test_helpers.rs
index 3c5f8a2984dd..f2a0f1063c15 100644
--- a/rust/feature-flags/src/flags/test_helpers.rs
+++ b/rust/feature-flags/src/flags/test_helpers.rs
@@ -46,7 +46,7 @@ pub async fn get_flags_from_redis(
team_id,
e
);
- FlagError::DataParsingErrorWithContext(format!(
+ FlagError::flag_data_parsing(format!(
"Failed to deserialize pickle data for team {team_id}: {}",
simplify_serde_error(&e.to_string())
))
@@ -59,7 +59,7 @@ pub async fn get_flags_from_redis(
team_id,
e
);
- FlagError::DataParsingErrorWithContext(format!(
+ FlagError::flag_data_parsing(format!(
"Failed to parse hypercache JSON for team {team_id}: {}",
simplify_serde_error(&e.to_string())
))
@@ -108,7 +108,7 @@ pub async fn update_flags_in_hypercache(
team_id,
e
);
- FlagError::DataParsingErrorWithContext(format!(
+ FlagError::flag_data_parsing(format!(
"Failed to serialize flags for team {team_id}: {}",
simplify_serde_error(&e.to_string())
))
@@ -121,7 +121,7 @@ pub async fn update_flags_in_hypercache(
team_id,
e
);
- FlagError::DataParsingErrorWithContext(format!(
+ FlagError::flag_data_parsing(format!(
"Failed to pickle flags for team {team_id}: {}",
simplify_serde_error(&e.to_string())
))
@@ -142,7 +142,7 @@ pub async fn update_flags_in_hypercache(
.await
.map_err(|e| {
tracing::error!("Failed to update hypercache for project {}: {}", team_id, e);
- FlagError::Internal(format!("Failed to update cache: {e}"))
+ FlagError::internal(anyhow::anyhow!("Failed to update cache: {e}"))
})?;
// Mirror Django's `HyperCache._set_cache_value_redis` (enable_etag=True),
@@ -160,7 +160,7 @@ pub async fn update_flags_in_hypercache(
team_id,
e
);
- FlagError::Internal(format!("Failed to write etag: {e}"))
+ FlagError::internal(anyhow::anyhow!("Failed to write etag: {e}"))
})?;
Ok(())
diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rs
index 9eca4660fa60..11e14489e5de 100644
--- a/rust/feature-flags/src/handler/canonical_log.rs
+++ b/rust/feature-flags/src/handler/canonical_log.rs
@@ -1198,7 +1198,7 @@ mod tests {
503,
"service_unavailable"
)]
- #[case(FlagError::Internal("test".into()), 500, "internal_error")]
+ #[case(FlagError::internal(anyhow::anyhow!("test")), 500, "internal_error")]
#[case(FlagError::RequestDecodingError("test".into()), 400, "request_decoding_error")]
#[case(FlagError::MissingDistinctId, 400, "missing_distinct_id")]
#[case(FlagError::NoTokenError, 401, "missing_token")]
@@ -1207,8 +1207,8 @@ mod tests {
#[case(FlagError::SecretApiTokenInvalid, 401, "secret_api_token_invalid")]
#[case(FlagError::NoAuthenticationProvided, 401, "no_authentication")]
#[case(FlagError::RowNotFound, 500, "row_not_found")]
- #[case(FlagError::DataParsingErrorWithContext("test".into()), 500, "flag_data_parsing_error")]
- #[case(FlagError::RedisUnavailable, 503, "redis_unavailable")]
+ #[case(FlagError::flag_data_parsing("test"), 500, "flag_data_parsing_error")]
+ #[case(FlagError::redis_unavailable(anyhow::anyhow!("connection refused")), 503, "redis_unavailable")]
#[case(FlagError::DatabaseUnavailable, 503, "database_unavailable")]
#[case(FlagError::TimeoutError(None), 503, "timeout")]
#[case(FlagError::TimeoutError(Some("pool".into())), 503, "timeout")]
@@ -1227,9 +1227,14 @@ mod tests {
500,
"cohort_filters_parsing_error"
)]
- #[case(FlagError::PersonNotFound, 503, "person_not_found")]
- #[case(FlagError::CacheMiss, 503, "cache_miss")]
- #[case(FlagError::DataParsingError, 500, "data_parsing_error")]
+ #[case(FlagError::person_not_found(), 503, "person_not_found")]
+ #[case(FlagError::cache_miss(), 503, "cache_miss")]
+ #[case(FlagError::data_parsing(anyhow::anyhow!("bad payload")), 500, "data_parsing_error")]
+ #[case(
+ FlagError::batch_evaluation_panicked(),
+ 500,
+ "batch_evaluation_panicked"
+ )]
#[case(FlagError::HashKeyOverrideError, 500, "hash_key_override_error")]
fn test_set_error_populates_fields(
#[case] error: FlagError,
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index eb4d2471e8d8..1bec7b18a842 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -578,7 +578,7 @@ mod metrics_tests {
fn test_record_metrics_with_5xx_error() {
clear_recorded_metrics();
- let result = Err(FlagError::Internal("test error".to_string()));
+ let result = Err(FlagError::internal(anyhow::anyhow!("test error")));
let data = MetricsData {
team_id: Some(456),
flags_disabled: Some(true),
diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rs
index a68b89c6af1c..0e55975889c5 100644
--- a/rust/feature-flags/tests/test_flag_definitions.rs
+++ b/rust/feature-flags/tests/test_flag_definitions.rs
@@ -1123,13 +1123,13 @@ async fn test_cache_miss_returns_503() {
body["detail"]
.as_str()
.unwrap()
- .contains("Required data not found in cache"),
+ .contains("A service dependency is temporarily unavailable"),
"Error message should mention cache miss"
);
} else {
// If not JSON, verify the error message mentions cache
assert!(
- body_text.contains("Required data not found in cache"),
+ body_text.contains("A service dependency is temporarily unavailable"),
"Body should mention cache miss. Got: {body_text}"
);
}
diff --git a/rust/feature-flags/tests/test_remote_config.rs b/rust/feature-flags/tests/test_remote_config.rs
index 502ae416270a..37687dd5f7e0 100644
--- a/rust/feature-flags/tests/test_remote_config.rs
+++ b/rust/feature-flags/tests/test_remote_config.rs
@@ -1380,7 +1380,7 @@ async fn test_remote_config_token_without_auth_returns_401() {
#[tokio::test]
async fn test_remote_config_personal_key_no_decryptor_returns_500() {
// With no FLAGS_SECRET_KEYS/SECRET_KEY the decryptor is None; an encrypted-flag decrypt
- // request must 500 (FlagError::Internal), never leak ciphertext.
+ // request must 500 (FlagError::RemoteConfigDecryptFailed), never leak ciphertext.
let mut config = Config::default_test_config();
config.flags_secret_keys = String::new();
config.secret_key = String::new();