Skip to main content

gqlrs_warp/
error.rs

1use std::{
2    error::Error,
3    fmt::{self, Display, Formatter},
4};
5
6use async_graphql::ParseRequestError;
7use warp::{Reply, http::StatusCode, reject::Reject};
8
9/// Bad request error.
10///
11/// It's a wrapper of `async_graphql::ParseRequestError`. It is also a `Reply` -
12/// by default it just returns a response containing the error message in plain
13/// text.
14#[derive(Debug)]
15pub struct GraphQLBadRequest(pub ParseRequestError);
16
17impl GraphQLBadRequest {
18    /// Get the appropriate status code of the error.
19    #[must_use]
20    pub fn status(&self) -> StatusCode {
21        match self.0 {
22            ParseRequestError::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
23            _ => StatusCode::BAD_REQUEST,
24        }
25    }
26}
27
28impl Display for GraphQLBadRequest {
29    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30        self.0.fmt(f)
31    }
32}
33
34impl Error for GraphQLBadRequest {
35    fn source(&self) -> Option<&(dyn Error + 'static)> {
36        Some(&self.0)
37    }
38}
39
40impl Reject for GraphQLBadRequest {}
41
42impl Reply for GraphQLBadRequest {
43    fn into_response(self) -> warp::reply::Response {
44        warp::reply::with_status(self.0.to_string(), self.status()).into_response()
45    }
46}
47
48impl From<ParseRequestError> for GraphQLBadRequest {
49    fn from(e: ParseRequestError) -> Self {
50        Self(e)
51    }
52}
53
54impl From<GraphQLBadRequest> for ParseRequestError {
55    fn from(e: GraphQLBadRequest) -> Self {
56        e.0
57    }
58}