axum_service_errors/
lib.rs1use std::borrow::Cow;
2
3use axum::{
4 Json,
5 http::StatusCode,
6 response::{IntoResponse, Response},
7};
8
9#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
11pub struct ServiceError<'a> {
12 pub code: u32,
15 #[serde(borrow)]
17 pub name: Cow<'a, str>,
18 pub http_status: u16,
20 #[serde(borrow)]
22 pub message: Cow<'a, str>,
23}
24
25impl<'a> ServiceError<'a> {
26 pub const fn new(code: u32, name: &'a str, status: u16, message: &'a str) -> Self {
28 Self {
29 code,
30 name: Cow::Borrowed(name),
31 http_status: status,
32 message: Cow::Borrowed(message),
33 }
34 }
35}
36
37impl<'a> IntoResponse for ServiceError<'a> {
38 fn into_response(self) -> Response {
39 let status_code =
42 StatusCode::from_u16(self.http_status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
43
44 (status_code, Json(self)).into_response()
45 }
46}