Struct async_graphql::ServerError
source · pub struct ServerError {
pub message: String,
pub source: Option<Arc<dyn Any + Send + Sync>>,
pub locations: Vec<Pos>,
pub path: Vec<PathSegment>,
pub extensions: Option<ErrorExtensionValues>,
}
Expand description
An error in a GraphQL server.
Fields§
§message: String
An explanatory message of the error.
source: Option<Arc<dyn Any + Send + Sync>>
The source of the error.
locations: Vec<Pos>
Where the error occurred.
path: Vec<PathSegment>
If the error occurred in a resolver, the path to the error.
extensions: Option<ErrorExtensionValues>
Extensions to the error.
Implementations§
source§impl ServerError
impl ServerError
sourcepub fn new(message: impl Into<String>, pos: Option<Pos>) -> Self
pub fn new(message: impl Into<String>, pos: Option<Pos>) -> Self
Create a new server error with the message.
Examples found in repository?
More examples
src/dynamic/schema.rs (line 252)
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
fn query_root(&self) -> ServerResult<&Object> {
self.0
.types
.get(&self.0.env.registry.query_type)
.and_then(Type::as_object)
.ok_or_else(|| ServerError::new("Query root not found", None))
}
fn mutation_root(&self) -> ServerResult<&Object> {
self.0
.env
.registry
.mutation_type
.as_ref()
.and_then(|mutation_name| self.0.types.get(mutation_name))
.and_then(Type::as_object)
.ok_or_else(|| ServerError::new("Mutation root not found", None))
}
fn subscription_root(&self) -> ServerResult<&Subscription> {
self.0
.env
.registry
.subscription_type
.as_ref()
.and_then(|subscription_name| self.0.types.get(subscription_name))
.and_then(Type::as_subscription)
.ok_or_else(|| ServerError::new("Subscription root not found", None))
}
/// Returns SDL(Schema Definition Language) of this schema.
pub fn sdl(&self) -> String {
self.0.env.registry.export_sdl(Default::default())
}
/// Returns SDL(Schema Definition Language) of this schema with options.
pub fn sdl_with_options(&self, options: SDLExportOptions) -> String {
self.0.env.registry.export_sdl(options)
}
async fn execute_once(&self, env: QueryEnv, root_value: &FieldValue<'static>) -> Response {
// execute
let ctx = env.create_context(&self.0.env, None, &env.operation.node.selection_set);
let res = match &env.operation.node.ty {
OperationType::Query => {
async move { self.query_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, false)
})
.await
}
OperationType::Mutation => {
async move { self.mutation_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, true)
})
.await
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value.unwrap_or_default()),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
src/types/empty_subscription.rs (line 48)
40 41 42 43 44 45 46 47 48 49 50 51
fn create_field_stream<'a>(
&'a self,
_ctx: &'a Context<'_>,
) -> Option<Pin<Box<dyn Stream<Item = Response> + Send + 'a>>>
where
Self: Send + Sync + 'static + Sized,
{
Some(Box::pin(stream::once(async move {
let err = ServerError::new("Schema is not configured for subscription.", None);
Response::from_errors(vec![err])
})))
}
src/context.rs (line 566)
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
fn var_value(&self, name: &str, pos: Pos) -> ServerResult<Value> {
self.query_env
.operation
.node
.variable_definitions
.iter()
.find(|def| def.node.name.node == name)
.and_then(|def| {
self.query_env
.variables
.get(&def.node.name.node)
.or_else(|| def.node.default_value())
})
.cloned()
.ok_or_else(|| {
ServerError::new(format!("Variable {} is not defined.", name), Some(pos))
})
}
src/schema.rs (lines 464-467)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
async fn execute_once(&self, env: QueryEnv) -> Response {
// execute
let ctx = ContextBase {
path_node: None,
is_for_introspection: false,
item: &env.operation.node.selection_set,
schema_env: &self.0.env,
query_env: &env,
};
let res = match &env.operation.node.ty {
OperationType::Query => resolve_container(&ctx, &self.0.query).await,
OperationType::Mutation => {
if self.0.env.registry.introspection_mode == IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
resolve_container_serial(&ctx, &EmptyMutation).await
} else {
resolve_container_serial(&ctx, &self.0.mutation).await
}
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
/// Execute a GraphQL query.
pub async fn execute(&self, request: impl Into<Request>) -> Response {
let request = request.into();
let extensions = self.create_extensions(Default::default());
let request_fut = {
let extensions = extensions.clone();
async move {
match prepare_request(
extensions,
request,
Default::default(),
&self.0.env.registry,
self.0.validation_mode,
self.0.recursive_depth,
self.0.complexity,
self.0.depth,
)
.await
{
Ok((env, cache_control)) => {
let fut = async {
self.execute_once(env.clone())
.await
.cache_control(cache_control)
};
futures_util::pin_mut!(fut);
env.extensions
.execute(env.operation_name.as_deref(), &mut fut)
.await
}
Err(errors) => Response::from_errors(errors),
}
}
};
futures_util::pin_mut!(request_fut);
extensions.request(&mut request_fut).await
}
/// Execute a GraphQL batch query.
pub async fn execute_batch(&self, batch_request: BatchRequest) -> BatchResponse {
match batch_request {
BatchRequest::Single(request) => BatchResponse::Single(self.execute(request).await),
BatchRequest::Batch(requests) => BatchResponse::Batch(
futures_util::stream::iter(requests.into_iter())
.then(|request| self.execute(request))
.collect()
.await,
),
}
}
/// Execute a GraphQL subscription with session data.
pub fn execute_stream_with_session_data(
&self,
request: impl Into<Request>,
session_data: Arc<Data>,
) -> impl Stream<Item = Response> + Send + Unpin {
let schema = self.clone();
let request = request.into();
let extensions = self.create_extensions(session_data.clone());
let stream = futures_util::stream::StreamExt::boxed({
let extensions = extensions.clone();
let env = self.0.env.clone();
async_stream::stream! {
let (env, cache_control) = match prepare_request(
extensions, request, session_data, &env.registry,
schema.0.validation_mode, schema.0.recursive_depth, schema.0.complexity, schema.0.depth
).await {
Ok(res) => res,
Err(errors) => {
yield Response::from_errors(errors);
return;
}
};
if env.operation.node.ty != OperationType::Subscription {
yield schema.execute_once(env).await.cache_control(cache_control);
return;
}
let ctx = env.create_context(
&schema.0.env,
None,
&env.operation.node.selection_set,
);
let mut streams = Vec::new();
let collect_result = if schema.0.env.registry.introspection_mode
== IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
collect_subscription_streams(&ctx, &EmptySubscription, &mut streams)
} else {
collect_subscription_streams(&ctx, &schema.0.subscription, &mut streams)
};
if let Err(err) = collect_result {
yield Response::from_errors(vec![err]);
}
let mut stream = stream::select_all(streams);
while let Some(resp) = stream.next().await {
yield resp;
}
}
});
extensions.subscribe(stream)
}
/// Execute a GraphQL subscription.
pub fn execute_stream(
&self,
request: impl Into<Request>,
) -> impl Stream<Item = Response> + Send + Unpin {
self.execute_stream_with_session_data(request, Default::default())
}
}
#[async_trait::async_trait]
impl<Query, Mutation, Subscription> Executor for Schema<Query, Mutation, Subscription>
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
async fn execute(&self, request: Request) -> Response {
Schema::execute(self, request).await
}
fn execute_stream(
&self,
request: Request,
session_data: Option<Arc<Data>>,
) -> BoxStream<'static, Response> {
Schema::execute_stream_with_session_data(&self, request, session_data.unwrap_or_default())
.boxed()
}
}
fn check_recursive_depth(doc: &ExecutableDocument, max_depth: usize) -> ServerResult<()> {
fn check_selection_set(
doc: &ExecutableDocument,
selection_set: &Positioned<SelectionSet>,
current_depth: usize,
max_depth: usize,
) -> ServerResult<()> {
if current_depth > max_depth {
return Err(ServerError::new(
format!(
"The recursion depth of the query cannot be greater than `{}`",
max_depth
),
Some(selection_set.pos),
));
}
for selection in &selection_set.node.items {
match &selection.node {
Selection::Field(field) => {
if !field.node.selection_set.node.items.is_empty() {
check_selection_set(
doc,
&field.node.selection_set,
current_depth + 1,
max_depth,
)?;
}
}
Selection::FragmentSpread(fragment_spread) => {
if let Some(fragment) =
doc.fragments.get(&fragment_spread.node.fragment_name.node)
{
check_selection_set(
doc,
&fragment.node.selection_set,
current_depth + 1,
max_depth,
)?;
}
}
Selection::InlineFragment(inline_fragment) => {
check_selection_set(
doc,
&inline_fragment.node.selection_set,
current_depth + 1,
max_depth,
)?;
}
}
}
Ok(())
}
for (_, operation) in doc.operations.iter() {
check_selection_set(doc, &operation.node.selection_set, 0, max_depth)?;
}
Ok(())
}
fn remove_skipped_selection(selection_set: &mut SelectionSet, variables: &Variables) {
fn is_skipped(directives: &[Positioned<Directive>], variables: &Variables) -> bool {
for directive in directives {
let include = match &*directive.node.name.node {
"skip" => false,
"include" => true,
_ => continue,
};
if let Some(condition_input) = directive.node.get_argument("if") {
let value = condition_input
.node
.clone()
.into_const_with(|name| variables.get(&name).cloned().ok_or(()))
.unwrap_or_default();
let value: bool = InputType::parse(Some(value)).unwrap_or_default();
if include != value {
return true;
}
}
}
false
}
selection_set
.items
.retain(|selection| !is_skipped(selection.node.directives(), variables));
for selection in &mut selection_set.items {
selection.node.directives_mut().retain(|directive| {
directive.node.name.node != "skip" && directive.node.name.node != "include"
});
}
for selection in &mut selection_set.items {
match &mut selection.node {
Selection::Field(field) => {
remove_skipped_selection(&mut field.node.selection_set.node, variables);
}
Selection::FragmentSpread(_) => {}
Selection::InlineFragment(inline_fragment) => {
remove_skipped_selection(&mut inline_fragment.node.selection_set.node, variables);
}
}
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn prepare_request(
mut extensions: Extensions,
request: Request,
session_data: Arc<Data>,
registry: &Registry,
validation_mode: ValidationMode,
recursive_depth: usize,
complexity: Option<usize>,
depth: Option<usize>,
) -> Result<(QueryEnv, CacheControl), Vec<ServerError>> {
let mut request = request;
let query_data = Arc::new(std::mem::take(&mut request.data));
extensions.attach_query_data(query_data.clone());
let mut request = extensions.prepare_request(request).await?;
let mut document = {
let query = &request.query;
let parsed_doc = request.parsed_query.take();
let fut_parse = async move {
let doc = match parsed_doc {
Some(parsed_doc) => parsed_doc,
None => parse_query(query)?,
};
check_recursive_depth(&doc, recursive_depth)?;
Ok(doc)
};
futures_util::pin_mut!(fut_parse);
extensions
.parse_query(query, &request.variables, &mut fut_parse)
.await?
};
// check rules
let validation_result = {
let validation_fut = async {
check_rules(
registry,
&document,
Some(&request.variables),
validation_mode,
)
};
futures_util::pin_mut!(validation_fut);
extensions.validation(&mut validation_fut).await?
};
// check limit
if let Some(limit_complexity) = complexity {
if validation_result.complexity > limit_complexity {
return Err(vec![ServerError::new("Query is too complex.", None)]);
}
}
if let Some(limit_depth) = depth {
if validation_result.depth > limit_depth {
return Err(vec![ServerError::new("Query is nested too deep.", None)]);
}
}
let operation = if let Some(operation_name) = &request.operation_name {
match document.operations {
DocumentOperations::Single(_) => None,
DocumentOperations::Multiple(mut operations) => operations
.remove(operation_name.as_str())
.map(|operation| (Some(operation_name.clone()), operation)),
}
.ok_or_else(|| {
ServerError::new(
format!(r#"Unknown operation named "{}""#, operation_name),
None,
)
})
} else {
match document.operations {
DocumentOperations::Single(operation) => Ok((None, operation)),
DocumentOperations::Multiple(map) if map.len() == 1 => {
let (operation_name, operation) = map.into_iter().next().unwrap();
Ok((Some(operation_name.to_string()), operation))
}
DocumentOperations::Multiple(_) => Err(ServerError::new(
"Operation name required in request.",
None,
)),
}
};
let (operation_name, mut operation) = operation.map_err(|err| vec![err])?;
// remove skipped fields
for fragment in document.fragments.values_mut() {
remove_skipped_selection(&mut fragment.node.selection_set.node, &request.variables);
}
remove_skipped_selection(&mut operation.node.selection_set.node, &request.variables);
let env = QueryEnvInner {
extensions,
variables: request.variables,
operation_name,
operation,
fragments: document.fragments,
uploads: request.uploads,
session_data,
ctx_data: query_data,
extension_data: Arc::new(request.data),
http_headers: Default::default(),
introspection_mode: request.introspection_mode,
errors: Default::default(),
};
Ok((QueryEnv::new(env), validation_result.cache_control))
}
Additional examples can be found in:
sourcepub fn source<T: Any + Send + Sync>(&self) -> Option<&T>
pub fn source<T: Any + Send + Sync>(&self) -> Option<&T>
Get the source of the error.
Examples
use std::io::ErrorKind;
use async_graphql::*;
struct Query;
#[Object]
impl Query {
async fn value(&self) -> Result<i32> {
Err(Error::new_with_source(std::io::Error::new(
ErrorKind::Other,
"my error",
)))
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let err = schema
.execute("{ value }")
.await
.into_result()
.unwrap_err()
.remove(0);
assert!(err.source::<std::io::Error>().is_some());
Trait Implementations§
source§impl Clone for ServerError
impl Clone for ServerError
source§fn clone(&self) -> ServerError
fn clone(&self) -> ServerError
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for ServerError
impl Debug for ServerError
source§impl<'de> Deserialize<'de> for ServerError
impl<'de> Deserialize<'de> for ServerError
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Display for ServerError
impl Display for ServerError
source§impl From<Error> for ServerError
impl From<Error> for ServerError
source§impl From<ServerError> for Vec<ServerError>
impl From<ServerError> for Vec<ServerError>
source§fn from(single: ServerError) -> Self
fn from(single: ServerError) -> Self
Converts to this type from the input type.