commit c78b04c4350563eb9272518db38b3ae0b9c65698
parent cca31fd6bd8e04e16d92ecfe9dbd45eb38725a80
Author: Antoine A <>
Date: Thu, 19 Nov 2026 16:29:36 +0100
taler-api: accept error codes from other GANA registries
Diffstat:
4 files changed, 90 insertions(+), 49 deletions(-)
diff --git a/common/taler-api/src/error.rs b/common/taler-api/src/error.rs
@@ -33,9 +33,44 @@ use tracing::debug;
pub type ApiResult<T> = Result<T, ApiError>;
+/// Metadata supplied by an error code from a GANA registry
+pub trait GanaErrorCode {
+ fn value(&self) -> u32;
+ fn name(&self) -> &'static str;
+ fn description(&self) -> &'static str;
+ fn status_code(&self) -> u16;
+}
+
+impl GanaErrorCode for ErrorCode {
+ fn value(&self) -> u32 {
+ *self as u32
+ }
+
+ fn name(&self) -> &'static str {
+ self.as_str()
+ }
+
+ fn description(&self) -> &'static str {
+ ErrorCode::description(self)
+ }
+
+ fn status_code(&self) -> u16 {
+ self.status_code()
+ }
+}
+
+/// A numeric GANA error code with its symbolic name and description
+#[derive(Debug)]
+struct Code {
+ value: u32,
+ name: &'static str,
+ description: &'static str,
+}
+
#[derive(Debug, thiserror::Error)]
+#[error("{}", .hint.as_deref().unwrap_or(.code.description))]
pub struct ApiError {
- code: ErrorCode,
+ code: Code,
hint: Option<Box<str>>,
log: Option<Box<str>>,
status: Option<StatusCode>,
@@ -44,23 +79,17 @@ pub struct ApiError {
extra: Option<Box<RawValue>>,
}
-impl Display for ApiError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- if let Some(h) = &self.hint {
- f.write_str(h)
- } else {
- f.write_str(self.code.description())
- }
- }
-}
-
impl ApiError {
- pub fn new(code: ErrorCode) -> Self {
+ pub fn new(code: impl GanaErrorCode) -> Self {
Self {
- code,
+ code: Code {
+ value: code.value(),
+ name: code.name(),
+ description: code.description(),
+ },
hint: None,
log: None,
- status: None,
+ status: StatusCode::from_u16(code.status_code()).ok(),
path: None,
headers: None,
extra: None,
@@ -81,9 +110,9 @@ impl ApiError {
}
}
- pub fn with_status(self, code: StatusCode) -> Self {
+ pub fn with_status(self, status: StatusCode) -> Self {
Self {
- status: Some(code),
+ status: Some(status),
..self
}
}
@@ -124,15 +153,9 @@ impl From<sqlx::Error> for ApiError {
}
_ => (ErrorCode::GENERIC_DB_FETCH_FAILED, StatusCode::BAD_GATEWAY),
};
- Self {
- code,
- hint: None,
- status: Some(status),
- log: Some(format!("{value}").into_boxed_str()),
- path: None,
- headers: None,
- extra: None,
- }
+ Self::new(code)
+ .with_status(status)
+ .with_log(value.to_string())
}
}
@@ -253,14 +276,10 @@ impl IntoResponse for ApiError {
headers,
extra,
} = self;
- let status_code = status.unwrap_or_else(|| {
- StatusCode::from_u16(code.status_code()).expect("Invalid status code")
- });
-
let log = if let Some(log) = log {
// Hint contains sensitive data that is skipped in logs, reveal full hint if debugging
if let Some(hint) = &hint {
- debug!(target: "api", "{code} {hint}");
+ debug!(target: "api", "{} {hint}", code.name);
}
Some(log)
} else {
@@ -268,9 +287,9 @@ impl IntoResponse for ApiError {
};
let mut resp = (
- status_code,
+ status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
Json(ErrorDetail {
- code: code as u16,
+ code: code.value,
hint,
detail: None,
parameter: None,
@@ -290,8 +309,10 @@ impl IntoResponse for ApiError {
resp.headers_mut().append(k.unwrap(), v);
}
}
- resp.extensions_mut()
- .insert(LoggedError { code, info: log });
+ resp.extensions_mut().insert(LoggedError {
+ code: code.name,
+ info: log,
+ });
resp
}
@@ -299,19 +320,23 @@ impl IntoResponse for ApiError {
#[derive(Debug, Clone)]
pub struct LoggedError {
- pub code: ErrorCode,
+ pub code: &'static str,
pub info: Option<Box<str>>,
}
-pub fn failure_code(code: ErrorCode) -> ApiError {
+pub fn failure_code(code: impl GanaErrorCode) -> ApiError {
ApiError::new(code)
}
-pub fn failure(code: ErrorCode, hint: impl Display) -> ApiError {
+pub fn failure(code: impl GanaErrorCode, 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 GanaErrorCode,
+ hint: impl Display,
+ status: StatusCode,
+) -> ApiError {
ApiError::new(code).with_hint(hint).with_status(status)
}
diff --git a/common/taler-common/src/api.rs b/common/taler-common/src/api.rs
@@ -108,7 +108,7 @@ impl Display for LibtoolVersion {
/// <https://docs.taler.net/core/api-common.html#tsref-type-ErrorDetail>
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorDetail {
- pub code: u16,
+ pub code: u32,
pub hint: Option<Box<str>>,
pub detail: Option<Box<str>>,
pub parameter: Option<Box<str>>,
diff --git a/common/taler-macros/src/lib.rs b/common/taler-macros/src/lib.rs
@@ -200,9 +200,15 @@ pub fn derive_domain_code(input: TokenStream) -> TokenStream {
if enabled_str {
expanded.extend(quote! {
+ impl #name {
+ pub fn as_str(&self) -> &'static str {
+ match self { #(#as_ref_arms),* }
+ }
+ }
+
impl AsRef<str> for #name {
fn as_ref(&self) -> &str {
- match self { #(#as_ref_arms),* }
+ self.as_str()
}
}
diff --git a/common/taler-test-utils/src/server.rs b/common/taler-test-utils/src/server.rs
@@ -30,6 +30,7 @@ use axum::{
use flate2::{Compression, write::ZlibEncoder};
use http_body_util::BodyExt as _;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
+use taler_api::error::GanaErrorCode;
use taler_common::{api::ErrorDetail, encoding::base64, error_code::ErrorCode};
use tower::ServiceExt as _;
use tracing::warn;
@@ -292,9 +293,20 @@ impl TestResponse {
panic!("{method} {uri} expected {expected} got {status}");
} else {
let err: ErrorDetail = self.json_parse();
- let error: ErrorCode = ErrorCode::try_from(err.code).expect("Unknown error code");
let description = err.hint.unwrap_or_default();
- panic!("{method} {uri} expected {expected} got {status}: {error} {description}");
+ if let Ok(nb) = u16::try_from(err.code)
+ && let Ok(code) = ErrorCode::try_from(nb)
+ {
+ panic!(
+ "{method} {uri} expected {expected} got {status}: {} {description}",
+ code.name()
+ );
+ } else {
+ panic!(
+ "{method} {uri} expected {expected} got {status}: {} {description}",
+ err.code
+ );
+ }
}
}
}
@@ -332,11 +344,9 @@ impl TestResponse {
}
#[track_caller]
- pub fn assert_error(&self, error_code: ErrorCode) {
- self.assert_error_status(
- error_code,
- StatusCode::from_u16(error_code.status_code()).unwrap(),
- );
+ pub fn assert_error(&self, error_code: impl GanaErrorCode) {
+ let status = StatusCode::from_u16(error_code.status_code()).unwrap();
+ self.assert_error_status(error_code, status);
}
#[track_caller]
@@ -345,10 +355,10 @@ impl TestResponse {
}
#[track_caller]
- pub fn assert_error_status(&self, error_code: ErrorCode, status: StatusCode) {
+ pub fn assert_error_status(&self, error_code: impl GanaErrorCode, status: StatusCode) {
self.assert_status(status);
let err: ErrorDetail = self.json_parse();
- assert_eq!(error_code, ErrorCode::try_from(err.code).unwrap());
+ assert_eq!(error_code.value(), err.code);
}
#[track_caller]