build: add api server response envelope helpers
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{api_response::json_error_body, request_context::RequestContext};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AppError {
|
||||
status_code: StatusCode,
|
||||
@@ -14,17 +15,12 @@ pub struct AppError {
|
||||
details: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct LegacyApiErrorBody {
|
||||
error: LegacyApiErrorPayload,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct LegacyApiErrorPayload {
|
||||
code: &'static str,
|
||||
message: &'static str,
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ApiErrorPayload {
|
||||
pub code: &'static str,
|
||||
pub message: &'static str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
details: Option<Value>,
|
||||
pub details: Option<Value>,
|
||||
}
|
||||
|
||||
impl AppError {
|
||||
@@ -42,19 +38,26 @@ impl AppError {
|
||||
pub fn code(&self) -> &'static str {
|
||||
self.code
|
||||
}
|
||||
|
||||
pub fn into_response_with_context(self, request_context: Option<&RequestContext>) -> Response {
|
||||
let status_code = self.status_code;
|
||||
let payload = self.to_payload();
|
||||
|
||||
(status_code, json_error_body(request_context, &payload)).into_response()
|
||||
}
|
||||
|
||||
fn to_payload(&self) -> ApiErrorPayload {
|
||||
ApiErrorPayload {
|
||||
code: self.code,
|
||||
message: self.message,
|
||||
details: self.details.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let body = LegacyApiErrorBody {
|
||||
error: LegacyApiErrorPayload {
|
||||
code: self.code,
|
||||
message: self.message,
|
||||
details: self.details,
|
||||
},
|
||||
};
|
||||
|
||||
(self.status_code, Json(body)).into_response()
|
||||
self.into_response_with_context(None)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user