poem_openapi/types/
error.rs1use std::{fmt::Display, marker::PhantomData};
2
3use serde_json::Value;
4
5use super::Type;
6
7#[derive(Debug)]
12pub struct ParseError<T> {
13 message: String,
14 phantom: PhantomData<T>,
15}
16
17impl<T: Type, E: Display> From<E> for ParseError<T> {
18 fn from(error: E) -> Self {
19 Self::custom(error)
20 }
21}
22
23impl<T: Type> ParseError<T> {
24 fn new(message: String) -> Self {
25 Self {
26 message,
27 phantom: PhantomData,
28 }
29 }
30
31 #[must_use]
33 pub fn expected_type(actual: Value) -> Self {
34 Self::new(format!(
35 r#"Expected input type "{}", found {}."#,
36 T::name(),
37 actual
38 ))
39 }
40
41 #[must_use]
43 pub fn expected_input() -> Self {
44 Self::new(format!(r#"Type "{}" expects an input value."#, T::name()))
45 }
46
47 #[must_use]
52 pub fn custom(msg: impl Display) -> Self {
53 Self::new(format!(r#"failed to parse "{}": {}"#, T::name(), msg))
54 }
55
56 pub fn propagate<U: Type>(self) -> ParseError<U> {
58 if T::name() != U::name() {
59 ParseError::new(format!(
60 r#"{} (occurred while parsing "{}")"#,
61 self.message,
62 U::name()
63 ))
64 } else {
65 ParseError::new(self.message)
66 }
67 }
68
69 pub fn into_message(self) -> String {
71 self.message
72 }
73
74 pub fn message(&self) -> &str {
76 &self.message
77 }
78}
79
80pub type ParseResult<T> = Result<T, ParseError<T>>;