async-graphql/src/error.rs

350 lines
8.1 KiB
Rust
Raw Normal View History

use crate::{Pos, Value};
use std::fmt::{Debug, Display};
/// Input Value Error
#[derive(Debug)]
pub enum InputValueError {
/// Custom input value parsing error.
Custom(String),
/// The type of input value does not match the expectation.
ExpectedType(Value),
}
impl<T: Display> From<T> for InputValueError {
fn from(err: T) -> Self {
InputValueError::Custom(err.to_string())
}
}
impl InputValueError {
#[allow(missing_docs)]
pub fn into_error(self, pos: Pos, expected_type: String) -> Error {
match self {
InputValueError::Custom(reason) => Error::Query {
pos,
path: None,
err: QueryError::ParseInputValue { reason },
},
InputValueError::ExpectedType(value) => Error::Query {
pos,
path: None,
err: QueryError::ExpectedInputType {
expect: expected_type,
actual: value,
},
},
}
}
}
/// InputValueResult type
pub type InputValueResult<T> = std::result::Result<T, InputValueError>;
/// FieldError type
2020-04-02 04:57:53 +00:00
#[derive(Clone, Debug)]
pub struct FieldError(pub String, pub Option<serde_json::Value>);
impl FieldError {
#[doc(hidden)]
pub fn into_error(self, pos: Pos) -> Error {
Error::Query {
pos,
path: None,
err: QueryError::FieldError {
err: self.0,
extended_error: self.1,
},
}
}
2020-03-01 10:54:34 +00:00
#[doc(hidden)]
2020-05-20 00:18:28 +00:00
pub fn into_error_with_path(self, pos: Pos, path: Vec<serde_json::Value>) -> Error {
Error::Query {
pos,
2020-05-20 00:18:28 +00:00
path: if !path.is_empty() {
Some(path.into())
} else {
None
},
err: QueryError::FieldError {
err: self.0,
extended_error: self.1,
},
}
}
}
/// FieldResult type
pub type FieldResult<T> = std::result::Result<T, FieldError>;
impl<E> From<E> for FieldError
where
2020-04-02 04:57:53 +00:00
E: std::fmt::Display + Send + Sync + 'static,
{
fn from(err: E) -> Self {
2020-04-02 04:57:53 +00:00
FieldError(format!("{}", err), None)
}
}
#[allow(missing_docs)]
pub trait ErrorExtensions
where
Self: Sized,
{
fn extend(&self) -> FieldError;
fn extend_with<C>(self, cb: C) -> FieldError
where
C: FnOnce(&Self) -> serde_json::Value,
{
let name = self.extend().0;
if let Some(mut base) = self.extend().1 {
let mut cb_res = cb(&self);
if let Some(base_map) = base.as_object_mut() {
if let Some(cb_res_map) = cb_res.as_object_mut() {
base_map.append(cb_res_map);
}
return FieldError(name, Some(serde_json::json!(base_map)));
} else {
return FieldError(name, Some(cb_res));
}
}
FieldError(name, Some(cb(&self)))
}
}
impl ErrorExtensions for FieldError {
fn extend(&self) -> FieldError {
self.clone()
}
}
// implementing for &E instead of E gives the user the possibility to implement for E which does
// not conflict with this implementation acting as a fallback.
impl<E: std::fmt::Display> ErrorExtensions for &E {
fn extend(&self) -> FieldError {
FieldError(format!("{}", self), None)
}
}
#[allow(missing_docs)]
pub trait ResultExt<T, E>
where
Self: Sized,
{
fn extend_err<CB>(self, cb: CB) -> FieldResult<T>
where
CB: FnOnce(&E) -> serde_json::Value;
2020-04-02 04:57:53 +00:00
fn extend(self) -> FieldResult<T>;
}
2020-04-02 04:57:53 +00:00
// This is implemented on E and not &E which means it cannot be used on foreign types.
// (see example).
impl<T, E> ResultExt<T, E> for std::result::Result<T, E>
where
2020-04-02 04:57:53 +00:00
E: ErrorExtensions + Send + Sync + 'static,
{
fn extend_err<C>(self, cb: C) -> FieldResult<T>
where
C: FnOnce(&E) -> serde_json::Value,
{
match self {
2020-04-02 04:57:53 +00:00
Err(err) => Err(err.extend_with(|e| cb(e))),
Ok(value) => Ok(value),
}
}
fn extend(self) -> FieldResult<T> {
match self {
Err(err) => Err(err.extend()),
Ok(value) => Ok(value),
}
}
}
2020-03-01 10:54:34 +00:00
2020-03-20 03:56:08 +00:00
/// Error for query
2020-05-01 23:57:34 +00:00
#[derive(Debug, Error, PartialEq)]
2020-03-20 03:56:08 +00:00
#[allow(missing_docs)]
2020-03-01 13:35:39 +00:00
pub enum QueryError {
2020-03-01 10:54:34 +00:00
#[error("Not supported.")]
NotSupported,
#[error("Expected input type \"{expect}\", found {actual}.")]
ExpectedInputType {
2020-03-20 03:56:08 +00:00
/// Expect input type
expect: String,
/// Actual input type
actual: Value,
},
2020-03-01 10:54:34 +00:00
#[error("Failed to parse input value: {reason}")]
ParseInputValue { reason: String },
2020-03-01 10:54:34 +00:00
#[error("Cannot query field \"{field_name}\" on type \"{object}\".")]
2020-03-20 03:56:08 +00:00
FieldNotFound {
/// Field name
field_name: String,
/// Object name
object: String,
},
2020-03-01 10:54:34 +00:00
2020-03-14 03:46:20 +00:00
#[error("Missing operation")]
MissingOperation,
2020-03-01 10:54:34 +00:00
#[error("Unknown operation named \"{name}\"")]
2020-03-20 03:56:08 +00:00
UnknownOperationNamed {
/// Operation name for query
name: String,
},
2020-03-01 10:54:34 +00:00
#[error("Type \"{object}\" must have a selection of subfields.")]
2020-03-20 03:56:08 +00:00
MustHaveSubFields {
/// Object name
object: String,
},
2020-03-01 10:54:34 +00:00
#[error("Schema is not configured for mutations.")]
NotConfiguredMutations,
2020-03-17 09:26:59 +00:00
#[error("Schema is not configured for subscriptions.")]
NotConfiguredSubscriptions,
2020-03-02 00:24:49 +00:00
#[error("Invalid value for enum \"{ty}\".")]
2020-03-20 03:56:08 +00:00
InvalidEnumValue {
/// Enum type name
ty: String,
/// Enum value
value: String,
},
2020-03-01 13:35:39 +00:00
#[error("Required field \"{field_name}\" for InputObject \"{object}\" does not exist.")]
RequiredField {
2020-03-20 03:56:08 +00:00
/// field name
2020-03-01 13:35:39 +00:00
field_name: String,
2020-03-20 03:56:08 +00:00
/// object name
2020-03-01 13:35:39 +00:00
object: &'static str,
},
#[error("Variable \"${var_name}\" is not defined")]
2020-03-20 03:56:08 +00:00
VarNotDefined {
/// Variable name
var_name: String,
},
#[error(
"Directive \"{directive}\" argument \"{arg_name}\" of type \"{arg_type}\" is required, but it was not provided."
)]
RequiredDirectiveArgs {
2020-03-20 03:56:08 +00:00
/// Directive name
directive: &'static str,
2020-03-20 03:56:08 +00:00
/// Argument name
arg_name: &'static str,
2020-03-20 03:56:08 +00:00
/// Argument type
arg_type: &'static str,
},
#[error("Unknown directive \"{name}\".")]
2020-03-20 03:56:08 +00:00
UnknownDirective {
/// Directive name
name: String,
},
2020-03-05 07:50:57 +00:00
#[error("Unknown fragment \"{name}\".")]
2020-03-20 03:56:08 +00:00
UnknownFragment {
// Fragment name
name: String,
},
2020-03-07 02:39:55 +00:00
#[error("Too complex")]
2020-03-25 07:07:16 +00:00
TooComplex,
#[error("Too deep")]
2020-03-25 07:07:16 +00:00
TooDeep,
2020-03-01 10:54:34 +00:00
#[error("Failed to resolve field: {err}")]
FieldError {
2020-04-02 04:57:53 +00:00
err: String,
extended_error: Option<serde_json::Value>,
},
2020-04-09 14:03:09 +00:00
#[error("Entity not found")]
EntityNotFound,
#[error("\"__typename\" must be an existing string")]
TypeNameNotExists,
2020-03-01 10:54:34 +00:00
}
impl QueryError {
#[doc(hidden)]
pub fn into_error(self, pos: Pos) -> Error {
Error::Query {
pos,
path: None,
err: self,
2020-03-01 10:54:34 +00:00
}
}
}
#[allow(missing_docs)]
#[derive(Debug, Error)]
2020-04-14 01:53:17 +00:00
pub enum ParseRequestError {
#[error("{0}")]
2020-04-21 04:13:14 +00:00
Io(#[from] std::io::Error),
#[error("Invalid request: {0}")]
InvalidRequest(serde_json::Error),
#[error("Invalid files map: {0}")]
InvalidFilesMap(serde_json::Error),
2020-04-21 04:13:14 +00:00
#[error("Invalid multipart data")]
2020-05-18 01:32:55 +00:00
InvalidMultipart(multer::Error),
#[error("Missing \"operators\" part")]
MissingOperatorsPart,
#[error("Missing \"map\" part")]
MissingMapPart,
#[error("It's not an upload operation")]
NotUpload,
#[error("Missing files")]
MissingFiles,
2020-05-18 01:32:55 +00:00
#[error("Payload too large")]
PayloadTooLarge,
}
#[derive(Debug, PartialEq)]
pub struct RuleError {
pub locations: Vec<Pos>,
pub message: String,
}
#[allow(missing_docs)]
2020-05-01 23:57:34 +00:00
#[derive(Debug, Error, PartialEq)]
pub enum Error {
#[error("Parse error: {0}")]
Parse(#[from] crate::parser::Error),
#[error("Query error: {err}")]
Query {
pos: Pos,
path: Option<serde_json::Value>,
err: QueryError,
},
#[error("Rule error")]
Rule { errors: Vec<RuleError> },
}