use std::fmt;
use axum::{
Json,
http::{HeaderValue, StatusCode, header::CONTENT_TYPE},
response::{IntoResponse, Response},
};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
use thiserror::Error;
use crate::result::{
ClassifyError, ErrorBoundaryDecision, ErrorBoundaryPolicy, ErrorDescriptor, ErrorKind,
};
use super::request_context::{RequestContext, RequestId};
pub const PROBLEM_JSON_MEDIA_TYPE: &str = "application/problem+json";
pub const DEFAULT_PROBLEM_CODE: &str = "unknown_error";
pub const MAX_PROBLEM_CODE_LENGTH: usize = 128;
pub const MAX_PROBLEM_TYPE_LENGTH: usize = 2048;
const DEFAULT_PROBLEM_TYPE: &str = "about:blank";
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct ProblemCode(String);
impl ProblemCode {
pub fn new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
Self::try_new(value)
}
pub fn try_new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
let value = value.into().trim().to_owned();
validate_problem_code(&value)?;
Ok(Self(value))
}
#[must_use]
pub fn from_static(value: &'static str) -> Self {
Self::try_new(value).unwrap_or_else(|_| Self::unknown())
}
#[must_use]
pub fn unknown() -> Self {
Self(DEFAULT_PROBLEM_CODE.to_owned())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl std::fmt::Display for ProblemCode {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for ProblemCode {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::try_new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct ProblemType(String);
impl ProblemType {
pub fn new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
Self::try_new(value)
}
pub fn try_new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
let value = value.into().trim().to_owned();
validate_problem_type(&value)?;
Ok(Self(value))
}
#[must_use]
pub fn from_static(value: &'static str) -> Self {
Self::try_new(value).unwrap_or_else(|_| Self::about_blank())
}
#[must_use]
pub fn about_blank() -> Self {
Self(DEFAULT_PROBLEM_TYPE.to_owned())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl std::fmt::Display for ProblemType {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for ProblemType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::try_new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ProblemIdentifierError {
#[error("problem identifier must not be empty")]
Empty,
#[error("problem identifier must be less than or equal to {max} bytes")]
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("problem identifier contains unsupported characters")]
InvalidCharacters,
}
impl ClassifyError for ProblemIdentifierError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(match self {
Self::Empty => "problem_identifier_empty",
Self::TooLong { .. } => "problem_identifier_too_long",
Self::InvalidCharacters => "problem_identifier_invalid_characters",
})
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct ProblemDetails {
#[serde(rename = "type")]
pub type_uri: String,
pub title: String,
pub status: u16,
pub code: String,
pub detail: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trace_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<Value>,
}
impl fmt::Debug for ProblemDetails {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ProblemDetails")
.field("status", &self.status)
.field("code", &self.code)
.field("request_id", &self.request_id)
.field("trace_id", &self.trace_id)
.field("type_uri", &"[REDACTED]")
.field("title", &"[REDACTED]")
.field("detail", &"[REDACTED]")
.field("instance", &self.instance.as_ref().map(|_| "[REDACTED]"))
.field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
.field("context", &self.context.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
#[derive(Clone)]
pub struct ApiProblem {
status: StatusCode,
body: Box<ProblemDetails>,
}
impl fmt::Debug for ApiProblem {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ApiProblem")
.field("status", &self.status)
.field("body", &self.body)
.finish()
}
}
pub trait IntoApiProblem {
fn into_api_problem(self) -> ApiProblem;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCategory {
Validation,
Authentication,
Authorization,
NotFound,
Conflict,
RateLimit,
Dependency,
Internal,
}
impl ErrorCategory {
#[must_use]
pub const fn status(self) -> StatusCode {
match self {
Self::Validation => StatusCode::BAD_REQUEST,
Self::Authentication => StatusCode::UNAUTHORIZED,
Self::Authorization => StatusCode::FORBIDDEN,
Self::NotFound => StatusCode::NOT_FOUND,
Self::Conflict => StatusCode::CONFLICT,
Self::RateLimit => StatusCode::TOO_MANY_REQUESTS,
Self::Dependency => StatusCode::SERVICE_UNAVAILABLE,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl From<ErrorKind> for ErrorCategory {
fn from(kind: ErrorKind) -> Self {
match kind {
ErrorKind::Validation => Self::Validation,
ErrorKind::Authentication => Self::Authentication,
ErrorKind::Authorization => Self::Authorization,
ErrorKind::NotFound => Self::NotFound,
ErrorKind::Conflict => Self::Conflict,
ErrorKind::RateLimit => Self::RateLimit,
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => Self::Dependency,
ErrorKind::Internal => Self::Internal,
}
}
}
#[derive(Clone)]
pub struct PublicError {
category: ErrorCategory,
code: ProblemCode,
detail: String,
details: Option<Value>,
}
impl fmt::Debug for PublicError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PublicError")
.field("category", &self.category)
.field("code", &self.code)
.field("detail", &"[REDACTED]")
.field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
impl PublicError {
#[must_use]
pub fn new(category: ErrorCategory, code: ProblemCode, detail: impl Into<String>) -> Self {
Self {
category,
code,
detail: detail.into(),
details: None,
}
}
#[must_use]
pub fn validation(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::new(ErrorCategory::Validation, code, detail)
}
#[must_use]
pub fn dependency(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::new(ErrorCategory::Dependency, code, detail)
}
#[must_use]
pub fn internal(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::new(ErrorCategory::Internal, code, detail)
}
#[must_use]
pub fn from_descriptor(descriptor: ErrorDescriptor) -> Self {
Self::new(
ErrorCategory::from(descriptor.kind()),
ProblemCode::try_new(descriptor.code().as_str()).unwrap_or_else(|_| {
ProblemCode::unknown()
}),
descriptor.public_message(),
)
}
#[must_use]
pub fn with_details(mut self, details: Value) -> Self {
self.details = Some(details);
self
}
#[must_use]
pub const fn category(&self) -> ErrorCategory {
self.category
}
#[must_use]
pub fn code(&self) -> &ProblemCode {
&self.code
}
#[must_use]
pub fn detail(&self) -> &str {
&self.detail
}
}
impl IntoApiProblem for PublicError {
fn into_api_problem(self) -> ApiProblem {
let mut problem =
ApiProblem::from_valid_status(self.category.status(), self.code, self.detail);
if let Some(details) = self.details {
problem = problem.with_details(details);
}
problem
}
}
impl From<PublicError> for ApiProblem {
fn from(error: PublicError) -> Self {
error.into_api_problem()
}
}
impl ApiProblem {
pub fn new(
status: StatusCode,
code: ProblemCode,
detail: impl Into<String>,
) -> Result<Self, ApiProblemStatusError> {
Self::try_new(status, code, detail)
}
pub fn try_new(
status: StatusCode,
code: ProblemCode,
detail: impl Into<String>,
) -> Result<Self, ApiProblemStatusError> {
if !is_problem_status(status) {
return Err(ApiProblemStatusError::InvalidStatus {
status: status.as_u16(),
});
}
Ok(Self::from_valid_status(status, code, detail))
}
fn from_valid_status(status: StatusCode, code: ProblemCode, detail: impl Into<String>) -> Self {
Self {
status,
body: Box::new(ProblemDetails {
type_uri: ProblemType::about_blank().into_string(),
title: status.canonical_reason().unwrap_or("HTTP error").to_owned(),
detail: detail.into(),
status: status.as_u16(),
code: code.into_string(),
instance: None,
request_id: None,
trace_id: None,
details: None,
context: None,
}),
}
}
#[must_use]
pub fn bad_request(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::BAD_REQUEST, code, detail)
}
#[must_use]
pub fn unauthorized(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::UNAUTHORIZED, code, detail)
}
#[must_use]
pub fn forbidden(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::FORBIDDEN, code, detail)
}
#[must_use]
pub fn not_found(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::NOT_FOUND, code, detail)
}
#[must_use]
pub fn service_unavailable(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::SERVICE_UNAVAILABLE, code, detail)
}
#[must_use]
pub fn conflict(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::CONFLICT, code, detail)
}
#[must_use]
pub fn unprocessable_entity(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::UNPROCESSABLE_ENTITY, code, detail)
}
#[must_use]
pub fn payload_too_large(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::PAYLOAD_TOO_LARGE, code, detail)
}
#[must_use]
pub fn too_many_requests(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::TOO_MANY_REQUESTS, code, detail)
}
#[must_use]
pub fn internal_error() -> Self {
Self::from_valid_status(
StatusCode::INTERNAL_SERVER_ERROR,
ProblemCode::from_static("internal_error"),
"internal server error",
)
}
#[must_use]
pub fn with_request_id(mut self, request_id: &RequestId) -> Self {
self.body.request_id = Some(request_id.to_string());
self
}
#[must_use]
pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
let trace_id = trace_id.into();
if !trace_id.trim().is_empty() {
self.body.trace_id = Some(trace_id);
}
self
}
#[must_use]
pub fn with_request_context(mut self, context: &RequestContext) -> Self {
self.body.request_id = Some(context.request_id().to_string());
if let Some(trace_id) = context.trace_id() {
self.body.trace_id = Some(trace_id.to_owned());
}
if let Some(problem_context) = safe_problem_context(context) {
self.body.context = Some(problem_context);
}
self
}
#[must_use]
pub fn maybe_request_id(self, request_id: Option<&RequestId>) -> Self {
if let Some(request_id) = request_id {
self.with_request_id(request_id)
} else {
self
}
}
#[must_use]
pub fn with_type(mut self, type_uri: ProblemType) -> Self {
self.body.type_uri = type_uri.into_string();
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.body.title = title.into();
self
}
#[must_use]
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
self.body.instance = Some(instance.into());
self
}
#[must_use]
pub fn with_details(mut self, details: Value) -> Self {
self.body.details = Some(details);
self
}
#[must_use]
pub fn with_context(mut self, context: Value) -> Self {
self.body.context = Some(context);
self
}
#[must_use]
pub const fn status(&self) -> StatusCode {
self.status
}
#[must_use]
pub fn body(&self) -> &ProblemDetails {
&self.body
}
#[must_use]
pub fn into_body(self) -> ProblemDetails {
*self.body
}
}
#[derive(Debug, Clone, Copy)]
pub struct ApiErrorBoundary {
policy: ErrorBoundaryPolicy,
}
impl ApiErrorBoundary {
#[must_use]
pub const fn new(policy: ErrorBoundaryPolicy) -> Self {
Self { policy }
}
#[must_use]
pub const fn http_api() -> Self {
Self::new(ErrorBoundaryPolicy::http_api())
}
#[must_use]
pub const fn policy(&self) -> ErrorBoundaryPolicy {
self.policy
}
#[must_use]
pub fn decide<E>(&self, error: &E) -> ErrorBoundaryDecision
where
E: ClassifyError + ?Sized,
{
self.policy.decide(error)
}
#[must_use]
pub fn problem<E>(&self, error: &E, context: &RequestContext) -> ApiProblem
where
E: ClassifyError + ?Sized,
{
self.problem_from_decision(self.decide(error), context)
}
#[must_use]
pub fn problem_from_decision(
&self,
decision: ErrorBoundaryDecision,
context: &RequestContext,
) -> ApiProblem {
PublicError::from_descriptor(decision.into_descriptor())
.into_api_problem()
.with_request_context(context)
}
}
impl IntoApiProblem for ApiProblem {
fn into_api_problem(self) -> ApiProblem {
self
}
}
impl IntoResponse for ApiProblem {
fn into_response(self) -> Response {
let mut response = (self.status, Json(self.body)).into_response();
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
);
response
}
}
impl std::fmt::Display for ApiProblem {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"HTTP problem {} ({})",
self.body.code,
self.status.as_u16()
)
}
}
impl std::error::Error for ApiProblem {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ApiProblemStatusError {
#[error("problem status must be a 4xx or 5xx status code, got {status}")]
InvalidStatus {
#[doc = "The HTTP status code."]
status: u16,
},
}
impl ClassifyError for ApiProblemStatusError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("api_problem_invalid_status")
}
}
fn is_problem_status(status: StatusCode) -> bool {
status.is_client_error() || status.is_server_error()
}
fn validate_problem_code(value: &str) -> Result<(), ProblemIdentifierError> {
if value.is_empty() {
return Err(ProblemIdentifierError::Empty);
}
if value.len() > MAX_PROBLEM_CODE_LENGTH {
return Err(ProblemIdentifierError::TooLong {
max: MAX_PROBLEM_CODE_LENGTH,
});
}
if !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return Err(ProblemIdentifierError::InvalidCharacters);
}
Ok(())
}
fn validate_problem_type(value: &str) -> Result<(), ProblemIdentifierError> {
if value.is_empty() {
return Err(ProblemIdentifierError::Empty);
}
if value.len() > MAX_PROBLEM_TYPE_LENGTH {
return Err(ProblemIdentifierError::TooLong {
max: MAX_PROBLEM_TYPE_LENGTH,
});
}
if value
.bytes()
.any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
{
return Err(ProblemIdentifierError::InvalidCharacters);
}
Ok(())
}
fn safe_problem_context(context: &RequestContext) -> Option<Value> {
let mut value = Map::new();
insert_optional_string(&mut value, "client_ip", context.client_ip());
insert_optional_string(
&mut value,
"client_ip_source",
context.client_ip_source().map(|source| source.as_str()),
);
insert_optional_string(&mut value, "locale", context.locale());
insert_optional_string(&mut value, "time_zone", context.time_zone());
if let Some(offset) = context.utc_offset_minutes() {
value.insert("utc_offset_minutes".to_owned(), Value::from(offset));
}
insert_optional_string(&mut value, "client_id", context.client_id());
(!value.is_empty()).then_some(Value::Object(value))
}
fn insert_optional_string(map: &mut Map<String, Value>, key: &'static str, value: Option<&str>) {
if let Some(value) = value.filter(|value| !value.trim().is_empty()) {
map.insert(key.to_owned(), Value::String(value.to_owned()));
}
}
#[cfg(test)]
mod tests {
use axum::{http::StatusCode, response::IntoResponse};
use serde_json::json;
use super::{
ApiErrorBoundary, ApiProblem, ApiProblemStatusError, PROBLEM_JSON_MEDIA_TYPE, ProblemCode,
ProblemIdentifierError, ProblemType, PublicError, RequestContext, RequestId,
};
use crate::result::{ClassifyError, ErrorCode, ErrorDescriptor, ErrorKind};
fn code(value: &'static str) -> ProblemCode {
ProblemCode::from_static(value)
}
#[test]
fn validates_problem_code() {
let code = ProblemCode::try_new(" invalid_query ").expect("problem code should be valid");
assert_eq!(code.as_str(), "invalid_query");
assert!(matches!(
ProblemCode::try_new("invalid query"),
Err(ProblemIdentifierError::InvalidCharacters)
));
assert!(matches!(
ProblemCode::new("invalid query"),
Err(ProblemIdentifierError::InvalidCharacters)
));
}
#[test]
fn validates_problem_type() {
let problem_type = ProblemType::try_new(" https://example.com/problems/invalid-query ")
.expect("problem type should be valid");
assert_eq!(
problem_type.as_str(),
"https://example.com/problems/invalid-query"
);
assert!(matches!(
ProblemType::try_new("bad type"),
Err(ProblemIdentifierError::InvalidCharacters)
));
assert!(matches!(
ProblemType::new("bad type"),
Err(ProblemIdentifierError::InvalidCharacters)
));
}
#[test]
fn static_problem_identifiers_fall_back_without_panicking() {
assert_eq!(
ProblemCode::from_static("invalid code").as_str(),
"unknown_error"
);
assert_eq!(
ProblemType::from_static("invalid type").as_str(),
"about:blank"
);
}
#[test]
fn problem_identifiers_deserialize_with_constructor_validation() {
let code: ProblemCode =
serde_json::from_value(json!(" invalid_query ")).expect("code should deserialize");
assert_eq!(code.as_str(), "invalid_query");
assert!(serde_json::from_value::<ProblemCode>(json!("invalid query")).is_err());
let problem_type: ProblemType =
serde_json::from_value(json!(" https://example.com/problems/invalid-query "))
.expect("type should deserialize");
assert_eq!(
problem_type.as_str(),
"https://example.com/problems/invalid-query"
);
assert!(serde_json::from_value::<ProblemType>(json!("bad type")).is_err());
}
#[test]
fn problem_identifier_errors_are_classified_as_validation_failures() {
let error = ProblemCode::try_new("bad code").expect_err("problem code should be invalid");
let descriptor = error.error_descriptor();
assert_eq!(descriptor.kind(), ErrorKind::Validation);
assert_eq!(
descriptor.code().as_str(),
"problem_identifier_invalid_characters"
);
}
#[test]
fn problem_body_carries_status_and_request_id() {
let problem = ApiProblem::bad_request(code("invalid_query"), "invalid query")
.with_request_id(&RequestId::new("req_test").expect("request id should be valid"));
assert_eq!(problem.status(), StatusCode::BAD_REQUEST);
assert_eq!(problem.body().status, 400);
assert_eq!(problem.body().title, "Bad Request");
assert_eq!(problem.body().detail, "invalid query");
assert_eq!(problem.body().request_id.as_deref(), Some("req_test"));
}
#[test]
fn problem_debug_redacts_arbitrary_payloads_without_changing_wire_data() {
let detail = "private-public-detail";
let instance = "https://example.com/problem?token=private-instance";
let details = "private-details";
let context = "private-context";
let problem = ApiProblem::bad_request(code("invalid_query"), detail)
.with_instance(instance)
.with_details(json!({ "credential": details }))
.with_context(json!({ "session": context }));
let debug = format!("{problem:?}");
let display = problem.to_string();
assert!(debug.contains("invalid_query"));
assert!(debug.contains("[REDACTED]"));
for sensitive in [detail, instance, details, context] {
assert!(!debug.contains(sensitive));
assert!(!display.contains(sensitive));
}
assert_eq!(display, "HTTP problem invalid_query (400)");
let wire = serde_json::to_value(problem.body()).expect("problem should serialize");
assert_eq!(wire["detail"], detail);
assert_eq!(wire["instance"], instance);
assert_eq!(wire["details"]["credential"], details);
assert_eq!(wire["context"]["session"], context);
let public_error = PublicError::validation(code("invalid_query"), detail)
.with_details(json!({ "credential": details }));
let debug = format!("{public_error:?}");
assert!(!debug.contains(detail));
assert!(!debug.contains(details));
}
#[test]
fn request_context_enriches_problem_with_safe_correlation_fields() {
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01".to_owned()),
)
.with_client_ip("198.51.100.10")
.with_locale("en-US")
.with_time_zone("UTC")
.with_utc_offset_minutes(0)
.with_client_id("opsline")
.with_session_id("sess_private");
let problem = ApiProblem::bad_request(code("invalid_query"), "invalid query")
.with_request_context(&context)
.into_body();
assert_eq!(problem.request_id.as_deref(), Some("req_test"));
assert_eq!(
problem.trace_id.as_deref(),
Some("4bf92f3577b34da6a3ce929d0e0e4736")
);
assert_eq!(
problem.context,
Some(json!({
"client_id": "opsline",
"client_ip": "198.51.100.10",
"client_ip_source": "explicit",
"locale": "en-US",
"time_zone": "UTC",
"utc_offset_minutes": 0
}))
);
}
#[test]
fn api_error_boundary_maps_classified_errors_to_problem_details() {
let descriptor = ErrorDescriptor::new(
ErrorKind::Dependency,
ErrorCode::new("database_unavailable").expect("error code should be valid"),
"database connection failed",
);
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
None,
);
let problem = ApiErrorBoundary::http_api()
.problem(&descriptor, &context)
.into_body();
assert_eq!(problem.status, 503);
assert_eq!(problem.code, "database_unavailable");
assert_eq!(problem.detail, "service is unavailable");
assert_eq!(problem.request_id.as_deref(), Some("req_test"));
}
#[test]
fn problem_status_must_be_error_status() {
let error = ApiProblem::try_new(StatusCode::OK, code("ok"), "ok")
.expect_err("status is not an error");
assert!(matches!(
error,
ApiProblemStatusError::InvalidStatus { status: 200 }
));
assert_eq!(
error.error_descriptor().code().as_str(),
"api_problem_invalid_status"
);
assert!(ApiProblem::new(StatusCode::OK, code("ok"), "ok").is_err());
}
#[test]
fn response_uses_problem_json_content_type() {
let response =
ApiProblem::bad_request(code("invalid_query"), "invalid query").into_response();
let content_type = response
.headers()
.get(axum::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok());
assert_eq!(content_type, Some(PROBLEM_JSON_MEDIA_TYPE));
}
}