View Issue Details

IDProjectCategoryView StatusLast Update
0012176Talerexchangepublic2026-11-18 14:42
Reporterbot-cg [agent]  
PrioritynormalSeverityminor 
Status new 
Summary0012176: taler-api: accept error codes from other GANA registries
DescriptionApiError only took Taler's 16-bit ErrorCode, so a component with its own registry (Beekeeper uses 100000 to 110000) could not report its errors through it.

Files: common/taler-api/src/error.rs (paths in the taler-rust tree). The patch is attached; it is number 1 of the series in the parent issue, against taler-rust 2c678873, and applies on top of the patches before it.
TagsNo tags attached.
Attached Files
0001-api-accept-error-codes-from-other-GANA-registries.patch (7,389 bytes)   
From 17508aadb59ff7b6922e29e42c502abf9396f1a2 Mon Sep 17 00:00:00 2001
From: Christian Grothoff <christian@grothoff.org>
Date: Tue, 29 Sep 2026 13:48:22 +0200
Subject: [PATCH 1/9] api: accept error codes from other GANA registries

ApiError only took Taler's 16-bit ErrorCode, so a component with its own registry (Beekeeper uses 100000 to 110000) could not report its errors through it.
---
 common/taler-api/src/error.rs | 161 ++++++++++++++++++++++++++++++----
 1 file changed, 143 insertions(+), 18 deletions(-)

diff --git a/common/taler-api/src/error.rs b/common/taler-api/src/error.rs
index 02f1fe6..a6e5897 100644
--- a/common/taler-api/src/error.rs
+++ b/common/taler-api/src/error.rs
@@ -22,17 +22,114 @@ use axum::{
     http::{HeaderMap, HeaderValue, StatusCode, header::IntoHeaderName},
     response::{IntoResponse, Response},
 };
-use taler_common::{
-    api::{ErrorDetail, params::ParamsErr},
-    error_code::ErrorCode,
-    types::payto::PaytoErr,
-};
+use serde::Serialize;
+use taler_common::{api::params::ParamsErr, error_code::ErrorCode, types::payto::PaytoErr};
 
 pub type ApiResult<T> = Result<T, ApiError>;
 
+/// An error code with the HTTP status it is returned with.  Codes come from
+/// the GNU Taler registry ([`ErrorCode`]) or from another GANA registry, such
+/// as a component's own, whose values are above the Taler range (0 to 9999)
+/// and so may not fit in 16 bits.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Code {
+    value: u32,
+    status: u16,
+    source: Source,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Source {
+    Taler(ErrorCode),
+    Other {
+        name: &'static str,
+        description: &'static str,
+    },
+}
+
+impl Code {
+    /// A code from another registry.
+    pub const fn new(
+        value: u32,
+        status: u16,
+        name: &'static str,
+        description: &'static str,
+    ) -> Self {
+        Self {
+            value,
+            status,
+            source: Source::Other { name, description },
+        }
+    }
+
+    pub fn value(&self) -> u32 {
+        self.value
+    }
+
+    pub fn status(&self) -> u16 {
+        self.status
+    }
+
+    pub fn name(&self) -> &str {
+        match &self.source {
+            Source::Taler(code) => code.as_ref(),
+            Source::Other { name, .. } => name,
+        }
+    }
+
+    pub fn description(&self) -> &'static str {
+        match self.source {
+            Source::Taler(code) => code.description(),
+            Source::Other { description, .. } => description,
+        }
+    }
+
+    /// The Taler error code, if it is one.
+    pub fn taler(&self) -> Option<ErrorCode> {
+        match self.source {
+            Source::Taler(code) => Some(code),
+            Source::Other { .. } => None,
+        }
+    }
+}
+
+impl From<ErrorCode> for Code {
+    fn from(code: ErrorCode) -> Self {
+        Self {
+            value: code as u32,
+            status: code.status_code(),
+            source: Source::Taler(code),
+        }
+    }
+}
+
+impl Display for Code {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.write_str(self.name())
+    }
+}
+
+/// The body of an error response: `ErrorDetail`, with room for codes of more
+/// than 16 bits.
+#[derive(Serialize)]
+struct ErrorBody {
+    code: u32,
+    hint: Option<Box<str>>,
+    detail: Option<Box<str>>,
+    parameter: Option<Box<str>>,
+    path: Option<Box<str>>,
+    offset: Option<Box<str>>,
+    index: Option<Box<str>>,
+    object: Option<Box<str>>,
+    currency: Option<Box<str>>,
+    type_expected: Option<Box<str>>,
+    type_actual: Option<Box<str>>,
+    extra: Option<Box<serde_json::value::RawValue>>,
+}
+
 #[derive(Debug, thiserror::Error)]
 pub struct ApiError {
-    code: ErrorCode,
+    code: Code,
     hint: Option<Box<str>>,
     log: Option<Box<str>>,
     status: Option<StatusCode>,
@@ -51,9 +148,9 @@ impl Display for ApiError {
 }
 
 impl ApiError {
-    pub fn new(code: ErrorCode) -> Self {
+    pub fn new(code: impl Into<Code>) -> Self {
         Self {
-            code,
+            code: code.into(),
             hint: None,
             log: None,
             status: None,
@@ -112,7 +209,7 @@ impl From<sqlx::Error> for ApiError {
             _ => (ErrorCode::GENERIC_DB_FETCH_FAILED, StatusCode::BAD_GATEWAY),
         };
         Self {
-            code,
+            code: code.into(),
             hint: None,
             status: Some(status),
             log: Some(format!("{value}").into_boxed_str()),
@@ -189,15 +286,14 @@ impl IntoResponse for ApiError {
             path,
             headers,
         } = self;
-        let status_code = status.unwrap_or_else(|| {
-            StatusCode::from_u16(code.status_code()).expect("Invalid status code")
-        });
+        let status_code = status
+            .unwrap_or_else(|| StatusCode::from_u16(code.status()).expect("Invalid status code"));
         let log = log.or(hint.clone());
 
         let mut resp = (
             status_code,
-            Json(ErrorDetail {
-                code: code as u16,
+            Json(ErrorBody {
+                code: code.value(),
                 hint,
                 detail: None,
                 parameter: None,
@@ -226,19 +322,19 @@ impl IntoResponse for ApiError {
 
 #[derive(Debug, Clone)]
 pub struct LoggedError {
-    pub code: ErrorCode,
+    pub code: Code,
     pub info: Option<Box<str>>,
 }
 
-pub fn failure_code(code: ErrorCode) -> ApiError {
+pub fn failure_code(code: impl Into<Code>) -> ApiError {
     ApiError::new(code)
 }
 
-pub fn failure(code: ErrorCode, hint: impl Display) -> ApiError {
+pub fn failure(code: impl Into<Code>, hint: impl Display) -> ApiError {
     ApiError::new(code).with_hint(hint)
 }
 
-pub fn failure_status(code: ErrorCode, hint: impl Display, status: StatusCode) -> ApiError {
+pub fn failure_status(code: impl Into<Code>, hint: impl Display, status: StatusCode) -> ApiError {
     ApiError::new(code).with_hint(hint).with_status(status)
 }
 
@@ -257,3 +353,32 @@ 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 http_body_util::BodyExt as _;
+
+    use super::*;
+
+    async fn body(err: ApiError) -> (StatusCode, serde_json::Value) {
+        let resp = err.into_response();
+        let status = resp.status();
+        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
+        (status, serde_json::from_slice(&bytes).unwrap())
+    }
+
+    #[tokio::test]
+    async fn codes_from_other_registries() {
+        const OWN: Code = Code::new(100_000, 429, "OWN_RATE_LIMITED", "Too many requests.");
+        let (status, json) = body(failure(OWN, "slow down")).await;
+        assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
+        assert_eq!(json["code"], 100_000);
+        assert_eq!(json["hint"], "slow down");
+
+        let (status, json) = body(failure_code(ErrorCode::GENERIC_JSON_INVALID)).await;
+        assert_eq!(status, StatusCode::BAD_REQUEST);
+        assert_eq!(json["code"], ErrorCode::GENERIC_JSON_INVALID as u16);
+        // Same shape as ErrorDetail: absent fields are null.
+        assert!(json["detail"].is_null() && json.get("detail").is_some());
+    }
+}
-- 
2.47.3

Required notifications

Address or linkRemarkAdded byNotifiedActions

Relationships

child of 0012175 new taler-api: nine patches that Beekeeper carries on its vendored copy (patch series attached) 

Activities

bot-cg [agent]

2026-11-18 14:42

updater   ~0030575

Correction: this issue was filed in the category "exchange" by mistake. It concerns taler-rust (common/taler-api or common/taler-common), like its parent 0012175, and belongs in the category "taler-rust". This reporter account cannot change the category; could someone with updater rights move it?

Issue History

Date ModifiedUsernameFieldChange
2026-11-18 14:41bot-cgNew Issue
2026-11-18 14:41bot-cgRelationship addedchild of 0012175
2026-11-18 14:41bot-cgImplementer => oec
2026-11-18 14:41bot-cgReviewer => Christian Grothoff
2026-11-18 14:41bot-cgRelease signed by => Christian Grothoff
2026-11-18 14:41bot-cgDeployed by => Christian Grothoff
2026-11-18 14:41bot-cgVerifier => oec
2026-11-18 14:41bot-cgCommunicator => CM_7
2026-11-18 14:42bot-cgFile Added: 0001-api-accept-error-codes-from-other-GANA-registries.patch
2026-11-18 14:42bot-cgNote Added: 0030575