iroh_dns_server/http/
error.rs1use axum::{
2 Json,
3 extract::rejection::{ExtensionRejection, QueryRejection},
4 http::StatusCode,
5 response::IntoResponse,
6};
7use serde::{Deserialize, Serialize};
8
9pub(super) type AppResult<T> = Result<T, AppError>;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub(crate) struct AppError {
13 #[serde(with = "serde_status_code")]
14 status: StatusCode,
15 detail: Option<String>,
16}
17
18impl Default for AppError {
19 fn default() -> Self {
20 Self {
21 status: StatusCode::INTERNAL_SERVER_ERROR,
22 detail: None,
23 }
24 }
25}
26
27impl AppError {
28 pub(super) fn with_status(status: StatusCode) -> AppError {
29 Self {
30 status,
31 detail: None,
32 }
33 }
34
35 pub(super) fn new(status_code: StatusCode, message: Option<impl ToString>) -> AppError {
37 Self {
38 status: status_code,
39 detail: message.map(|m| m.to_string()),
41 }
42 }
43}
44
45impl IntoResponse for AppError {
46 fn into_response(self) -> axum::response::Response {
47 let json = Json(self.clone());
48 (self.status, json).into_response()
49 }
50}
51
52impl From<n0_error::AnyError> for AppError {
53 fn from(value: n0_error::AnyError) -> Self {
54 Self {
55 status: StatusCode::INTERNAL_SERVER_ERROR,
56 detail: Some(value.to_string()),
57 }
58 }
59}
60
61impl From<QueryRejection> for AppError {
62 fn from(value: QueryRejection) -> Self {
63 Self::new(StatusCode::BAD_REQUEST, Some(value))
64 }
65}
66
67impl From<ExtensionRejection> for AppError {
68 fn from(value: ExtensionRejection) -> Self {
69 Self::new(StatusCode::BAD_REQUEST, Some(value))
70 }
71}
72
73mod serde_status_code {
80 use http::StatusCode;
81 use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Unexpected};
82
83 pub(super) fn serialize<S: Serializer>(status: &StatusCode, ser: S) -> Result<S::Ok, S::Error> {
85 String::serialize(&status.as_u16().to_string(), ser)
86 }
87
88 pub(super) fn deserialize<'de, D>(de: D) -> Result<StatusCode, D::Error>
90 where
91 D: Deserializer<'de>,
92 {
93 let str = String::deserialize(de)?;
94 StatusCode::from_bytes(str.as_bytes()).map_err(|_| {
95 serde::de::Error::invalid_value(
96 Unexpected::Str(str.as_str()),
97 &"A valid http status code",
98 )
99 })
100 }
101}