nym_credential_proxy_lib/
http_helpers.rs1use crate::error::CredentialProxyError;
5use axum::Json;
6use axum::http::StatusCode;
7use axum::response::{IntoResponse, Response};
8use nym_credential_proxy_requests::api::v1::ErrorResponse;
9use tracing::warn;
10use uuid::Uuid;
11
12#[derive(Debug, Clone)]
13pub struct RequestError {
14 pub inner: ErrorResponse,
15 pub status: StatusCode,
16}
17
18impl RequestError {
19 pub fn new<S: Into<String>>(message: S, status: StatusCode) -> Self {
20 RequestError {
21 inner: ErrorResponse {
22 uuid: None,
23 message: message.into(),
24 },
25 status,
26 }
27 }
28
29 pub fn new_status(status: StatusCode) -> Self {
30 RequestError {
31 inner: ErrorResponse {
32 uuid: None,
33 message: String::new(),
34 },
35 status,
36 }
37 }
38
39 pub fn new_plain_error(err: CredentialProxyError) -> Self {
40 Self::from_err(err, StatusCode::INTERNAL_SERVER_ERROR)
41 }
42
43 pub fn new_server_error(err: CredentialProxyError, uuid: Uuid) -> Self {
44 RequestError::new_with_uuid(err.to_string(), uuid, StatusCode::INTERNAL_SERVER_ERROR)
45 }
46
47 pub fn new_with_uuid<S: Into<String>>(message: S, uuid: Uuid, status: StatusCode) -> Self {
48 RequestError {
49 inner: ErrorResponse {
50 uuid: Some(uuid),
51 message: message.into(),
52 },
53 status,
54 }
55 }
56
57 pub fn from_err<E: std::error::Error>(err: E, status: StatusCode) -> Self {
58 Self::new(err.to_string(), status)
59 }
60}
61
62impl IntoResponse for RequestError {
63 fn into_response(self) -> Response {
64 (self.status, Json(self.inner)).into_response()
65 }
66}
67
68pub fn db_failure<T>(err: CredentialProxyError, uuid: Uuid) -> Result<T, RequestError> {
69 warn!("db failure: {err}");
70 Err(RequestError::new_with_uuid(
71 format!("oh no, something went wrong {err}"),
72 uuid,
73 StatusCode::INTERNAL_SERVER_ERROR,
74 ))
75}