commit 76458c228b38ccfbebdc6e5fcf47f0c6f068f39b
parent 192f81951629522a59c5e409ff80d7fe6793b043
Author: Antoine A <>
Date: Thu, 19 Nov 2026 11:35:03 +0100
taler-api: allow extra details in error responses
Diffstat:
1 file changed, 37 insertions(+), 1 deletion(-)
diff --git a/common/taler-api/src/error.rs b/common/taler-api/src/error.rs
@@ -22,6 +22,7 @@ use axum::{
http::{HeaderMap, HeaderValue, StatusCode, header::IntoHeaderName},
response::{IntoResponse, Response},
};
+use serde_json::value::RawValue;
use taler_common::{
api::{ErrorDetail, params::ParamsErr},
error_code::ErrorCode,
@@ -38,6 +39,7 @@ pub struct ApiError {
status: Option<StatusCode>,
path: Option<Box<str>>,
headers: Option<Box<HeaderMap>>,
+ extra: Option<Box<RawValue>>,
}
impl Display for ApiError {
@@ -59,6 +61,7 @@ impl ApiError {
status: None,
path: None,
headers: None,
+ extra: None,
}
}
@@ -90,6 +93,14 @@ impl ApiError {
}
}
+ /// Include a JSON value in the error response's `extra` field.
+ pub fn with_extra(self, extra: Box<RawValue>) -> Self {
+ Self {
+ extra: Some(extra),
+ ..self
+ }
+ }
+
pub fn with_header(mut self, key: impl IntoHeaderName, value: HeaderValue) -> Self {
let headers = self.headers.get_or_insert_default();
headers.append(key, value);
@@ -118,6 +129,7 @@ impl From<sqlx::Error> for ApiError {
log: Some(format!("{value}").into_boxed_str()),
path: None,
headers: None,
+ extra: None,
}
}
}
@@ -194,6 +206,7 @@ impl IntoResponse for ApiError {
status,
path,
headers,
+ extra,
} = self;
let status_code = status.unwrap_or_else(|| {
StatusCode::from_u16(code.status_code()).expect("Invalid status code")
@@ -214,7 +227,7 @@ impl IntoResponse for ApiError {
currency: None,
type_expected: None,
type_actual: None,
- extra: None,
+ extra,
}),
)
.into_response();
@@ -263,3 +276,26 @@ pub fn forbidden(hint: impl Display) -> ApiError {
pub fn bad_request(hint: impl Display) -> ApiError {
ApiError::new(ErrorCode::GENERIC_JSON_INVALID).with_hint(hint)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::{Value, json, value::to_raw_value};
+
+ #[tokio::test]
+ async fn extra_details_in_response() {
+ let extra = json!({ "fields": ["amount", "currency"] });
+ let response = bad_request("invalid payment")
+ .with_extra(to_raw_value(&extra).unwrap())
+ .into_response();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body = axum::body::to_bytes(response.into_body(), 4096)
+ .await
+ .unwrap();
+ let body: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(body["code"], ErrorCode::GENERIC_JSON_INVALID as u16);
+ assert_eq!(body["hint"], "invalid payment");
+ assert_eq!(body["extra"], extra);
+ }
+}