From f0675b35328085ede7b3a31b13e5bf5f1f5b0c67 Mon Sep 17 00:00:00 2001 From: Christian Grothoff Date: Tue, 29 Sep 2026 13:48:51 +0200 Subject: [PATCH 2/9] api: allow extra details in error responses ErrorDetail has an extra field, but ApiError always sent it as null, so per-field validation problems had no place in the response. --- common/taler-api/src/error.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/common/taler-api/src/error.rs b/common/taler-api/src/error.rs index a6e5897..f6494ca 100644 --- a/common/taler-api/src/error.rs +++ b/common/taler-api/src/error.rs @@ -135,6 +135,7 @@ pub struct ApiError { status: Option, path: Option>, headers: Option>, + extra: Option>, } impl Display for ApiError { @@ -156,6 +157,7 @@ impl ApiError { status: None, path: None, headers: None, + extra: None, } } @@ -187,6 +189,18 @@ impl ApiError { } } + /// Set the `extra` field of the error response, for details that the + /// other fields cannot express (e.g. a list of validation problems). + pub fn with_extra(self, extra: &impl Serialize) -> Self { + match serde_json::value::to_raw_value(extra) { + Ok(raw) => Self { + extra: Some(raw), + ..self + }, + Err(e) => self.with_log(format!("unserializable error details: {e}")), + } + } + pub fn with_header(mut self, key: impl IntoHeaderName, value: HeaderValue) -> Self { let headers = self.headers.get_or_insert_default(); headers.append(key, value); @@ -215,6 +229,7 @@ impl From for ApiError { log: Some(format!("{value}").into_boxed_str()), path: None, headers: None, + extra: None, } } } @@ -285,6 +300,7 @@ impl IntoResponse for ApiError { status, path, headers, + extra, } = self; let status_code = status .unwrap_or_else(|| StatusCode::from_u16(code.status()).expect("Invalid status code")); @@ -304,7 +320,7 @@ impl IntoResponse for ApiError { currency: None, type_expected: None, type_actual: None, - extra: None, + extra, }), ) .into_response(); @@ -381,4 +397,12 @@ mod tests { // Same shape as ErrorDetail: absent fields are null. assert!(json["detail"].is_null() && json.get("detail").is_some()); } + + #[tokio::test] + async fn extra_details() { + let err = failure_code(ErrorCode::GENERIC_JSON_INVALID) + .with_extra(&serde_json::json!({"errors": {"name": ["required"]}})); + let (_, json) = body(err).await; + assert_eq!(json["extra"]["errors"]["name"][0], "required"); + } } -- 2.47.3