public override ErrorInfo GetInfo(ExecutionError executionError)
        {
            var info = base.GetInfo(executionError);

            info.Message = executionError switch
            {
                AuthorizationError authorizationError => GetAuthorizationErrorMessage(authorizationError),
                _ => info.Message,
            };
            return(info);
        }
示例#2
0
        internal static PersistedExecutionError ToPersistable(this ExecutionError instance)
        {
            var result = new PersistedExecutionError();

            result.ErrorTime          = instance.ErrorTime;
            result.Message            = instance.Message;
            result.ExecutionPointerId = instance.ExecutionPointerId;
            result.WorkflowId         = instance.WorkflowId;

            return(result);
        }
示例#3
0
    public static void EnrichWithErrorCode(ExecutionError error, Exception rootCause)
    {
        var code = rootCause.GetType().Name;

        if (code != "Exception")
        {
            code = code.Replace("Exception", string.Empty);
        }

        error.Extend("code", code.ToUpperInvariant());
    }
示例#4
0
        public static void Throw(ExecutionError error)
        {
            var description = error.GetType()
                              .GetField(error.ToString())
                              .GetCustomAttributes(typeof(DescriptionAttribute), false)
                              .Cast <DescriptionAttribute>()
                              .Single()
                              .Description;

            throw new ExecutionException(description);
        }
示例#5
0
 /// <summary>
 /// ブラウザの起動
 /// </summary>
 /// <param name="uri">表示するURL</param>
 public void RunBrowser(string uri)
 {
     try
     {
         Process.Start(uri);
     }
     catch (Exception e) when(e is Win32Exception || e is IOException)
     {
         Trace.TraceInformation($"ブラウザ起動失敗。{e.Message}:{uri}");
         ExecutionError?.Invoke(this, new ExecutionErrorEventArgs(ExecutionErrorEventArgs.Cause.WebBrowser, e, uri));
     }
 }
    public void drops_extensions_when_no_data()
    {
        var error = new ExecutionError(null);

        error.Code.ShouldBeNull();
        error.Data.ShouldNotBeNull();
        error.Data.Count.ShouldBe(0);

        var info = new ErrorInfoProvider().GetInfo(error);

        info.Extensions.ShouldBeNull();
    }
    public void verify_exposecodes_functionality_with_other_data()
    {
        var error = new ExecutionError("message", new ArgumentNullException())
        {
            Code = "code"
        };
        var info = new ErrorInfoProvider(opts => opts.ExposeCodes = false).GetInfo(error);

        info.Extensions.ShouldNotBeNull();
        info.Extensions.ShouldContainKey("code");
        info.Extensions.ShouldNotContainKey("codes");
    }
        /// <summary>
        /// Validates instance using DataAnnotations.
        /// </summary>
        /// <param name="instance">Validated instance.</param>
        /// <returns><see cref="FailedResult"/> if invalid, otherwise <see cref="SuccessfulResult"/>.</returns>
        public static IExecutionResult Validate(object instance)
        {
            if (instance == null)
            {
                return(new SuccessfulResult());
            }

            var validationContext = new ValidationContext(instance);
            var executionErrors   = new List <ExecutionError>();

            // Validate current level of the instance.
            CoreValidator.TryValidateObject(instance, validationContext, executionErrors, true);

            var instanceType = instance.GetType();
            var result       = new FailedResult(CoreErrorCodes.ValidationFailed, instanceType.Name);

            foreach (var executionError in executionErrors)
            {
                var field  = executionError.Source ?? string.Empty;
                var source = $"{instanceType.Name}.{field}";
                var error  = new ExecutionError(executionError.CodeInfo, source);

                result.AddError(error);
            }

            // Recursively validate nested types.
            var properties = instanceType
                             .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)
                             .Where(PropertyCanBeValidated);

            foreach (var property in properties)
            {
                var propertyValue = property.GetValue(instance);

                if (typeof(System.Collections.IEnumerable).IsAssignableFrom(property.PropertyType))
                {
                    UpdateFailedResultWithArrayElementsDetails(result, property, instanceType, propertyValue);
                    continue;
                }

                var propertyResult = Validate(propertyValue);
                if (!(propertyResult is FailedResult fr))
                {
                    continue;
                }

                UpdateFailedResultWithDetails(result, fr, property, instanceType);
            }

            return(result.Details.Any()
                ? (IExecutionResult)result
                : new SuccessfulResult());
        }
示例#9
0
        internal static WorkflowInstance ToWorkflowInstance(this PersistedWorkflow instance)
        {
            WorkflowInstance result = new WorkflowInstance();

            result.Data                 = JsonConvert.DeserializeObject(instance.Data, SerializerSettings);
            result.Description          = instance.Description;
            result.Id                   = instance.InstanceId.ToString();
            result.NextExecution        = instance.NextExecution;
            result.Version              = instance.Version;
            result.WorkflowDefinitionId = instance.WorkflowDefinitionId;
            result.Status               = instance.Status;
            result.CreateTime           = instance.CreateTime;
            result.CompleteTime         = instance.CompleteTime;

            foreach (var ep in instance.ExecutionPointers)
            {
                var pointer = new ExecutionPointer();
                result.ExecutionPointers.Add(pointer);

                pointer.Id              = ep.Id;
                pointer.StepId          = ep.StepId;
                pointer.Active          = ep.Active;
                pointer.SleepUntil      = ep.SleepUntil;
                pointer.PersistenceData = JsonConvert.DeserializeObject(ep.PersistenceData, SerializerSettings);
                pointer.StartTime       = ep.StartTime;
                pointer.EndTime         = ep.EndTime;
                pointer.StepName        = ep.StepName;
                pointer.EventName       = ep.EventName;
                pointer.EventKey        = ep.EventKey;
                pointer.EventPublished  = ep.EventPublished;
                pointer.ConcurrentFork  = ep.ConcurrentFork;
                pointer.PathTerminator  = ep.PathTerminator;
                pointer.EventData       = JsonConvert.DeserializeObject(ep.EventData, SerializerSettings);

                foreach (var attr in ep.ExtensionAttributes)
                {
                    pointer.ExtensionAttributes[attr.AttributeKey] = JsonConvert.DeserializeObject(attr.AttributeValue, SerializerSettings);
                }

                foreach (var err in ep.Errors)
                {
                    var execErr = new ExecutionError();
                    execErr.Id        = err.Id;
                    execErr.ErrorTime = err.ErrorTime;
                    execErr.Message   = err.Message;
                    pointer.Errors.Add(execErr);
                }
            }


            return(result);
        }
示例#10
0
 /// <summary>
 /// VirtualCastの起動
 /// </summary>
 public void RunVirtualCast()
 {
     try
     {
         Process.Start(UserSettingsService.UserSettings.VirtualCastExePath);
         VirtualCastLaunched?.Invoke(this, EventArgs.Empty);
     }
     catch (Exception e) when(e is Win32Exception || e is IOException)
     {
         Trace.TraceInformation($"バーチャルキャスト起動失敗。{e.Message}:{UserSettingsService.UserSettings.VirtualCastExePath}");
         ExecutionError?.Invoke(this, new ExecutionErrorEventArgs(ExecutionErrorEventArgs.Cause.VirtualCastExe, e, UserSettingsService.UserSettings.VirtualCastExePath));
     }
 }
        private ExecutionError GenerateError(
            ExecutionContext context,
            string message,
            Field field,
            IEnumerable <string> path,
            Exception ex = null)
        {
            var error = new ExecutionError(message, ex);

            error.AddLocation(field, context.Document);
            error.Path = path;
            return(error);
        }
示例#12
0
 public ExecutionErrors Transform(ExecutionErrors errors)
 => errors.Aggregate(new ExecutionErrors(), (result, executionError) =>
 {
     var exception = new FieldResolutionException(executionError);
     var error     = new ExecutionError(exception.Message, exception);
     foreach (var location in executionError.Locations ?? Enumerable.Empty <ErrorLocation>())
     {
         error.AddLocation(location.Line, location.Column);
     }
     error.Path = executionError.Path;
     result.Add(error);
     return(result);
 });
    public void verify_exposecode_functionality()
    {
        var error = new ExecutionError("message")
        {
            Code = "code"
        };
        var info = new ErrorInfoProvider(opts => opts.ExposeCode = false).GetInfo(error);

        info.Extensions.ShouldNotBeNull();
        info.Extensions.ShouldNotContainKey("code");
        info.Extensions.ShouldContainKey("codes");
        info.Extensions["codes"].ShouldBeAssignableTo <IEnumerable <object> >().ShouldBe(new[] { "code" });
    }
示例#14
0
        private void GenerateError(
            ExecutionContext context,
            Field field,
            Exception ex,
            IEnumerable <string> path)
        {
            var error = new ExecutionError("Error trying to resolve {0}.".ToFormat(field.Name), ex);

            error.AddLocation(field, context.Document);
            error.Path = path;

            context.Errors.Add(error);
        }
示例#15
0
 public void Insert(ExecutionError executionError)
 {
     using (var connection = _sqlConnectionFactory.CreateConnection())
     {
         connection.Execute(InsertSql, new
         {
             ReferenceType = executionError.ReferenceType.ToString(),
             ReferenceId   = executionError.ReferenceId,
             Message       = executionError.Message,
             Active        = executionError.Valid
         });
     }
 }
示例#16
0
        public void OnExecutionError(ExecutionEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e), $"{nameof(e)} is null.");
            }

            ExecutionError?.Invoke(this, e);
            if (!SuppressGlobalEvents && GlobalExecutionError != null)
            {
                GlobalExecutionError(this, e);
            }
        }
示例#17
0
        protected virtual void ValidateNodeResult(ExecutionContext context, ExecutionNode node)
        {
            var result = node.Result;

            IGraphType fieldType  = node.FieldDefinition.ResolvedType;
            var        objectType = fieldType as IObjectGraphType;

            if (fieldType is NonNullGraphType nonNullType)
            {
                objectType = nonNullType?.ResolvedType as IObjectGraphType;

                if (result == null)
                {
                    var type = nonNullType.ResolvedType;

                    var error = new ExecutionError($"Cannot return null for non-null type. Field: {node.Name}, Type: {type.Name}!.");
                    throw error;
                }
            }

            if (result == null)
            {
                return;
            }

            if (fieldType is IAbstractGraphType abstractType)
            {
                objectType = abstractType.GetObjectType(result);

                if (objectType == null)
                {
                    var error = new ExecutionError(
                        $"Abstract type {abstractType.Name} must resolve to an Object type at " +
                        $"runtime for field {node.Parent.GraphType.Name}.{node.Name} " +
                        $"with value {result}, received 'null'.");
                    throw error;
                }

                if (!abstractType.IsPossibleType(objectType))
                {
                    var error = new ExecutionError($"Runtime Object type \"{objectType}\" is not a possible type for \"{abstractType}\"");
                    throw error;
                }
            }

            if (objectType?.IsTypeOf != null && !objectType.IsTypeOf(result))
            {
                var error = new ExecutionError($"Expected value of type \"{objectType}\" but got: {result}.");
                throw error;
            }
        }
    public void verify_exposedata_functionality_with_other_data()
    {
        var error = new ExecutionError("message")
        {
            Code = "code"
        };

        error.Data["test"] = "abc";
        var info = new ErrorInfoProvider(opts => opts.ExposeData = false).GetInfo(error);

        info.Extensions.ShouldNotBeNull();
        info.Extensions.ShouldContainKey("code");
        info.Extensions.ShouldNotContainKey("data");
    }
    public void inner_exception_of_type_exception_does_serialize_extensions()
    {
        var error = new ExecutionError("Test execution error", new Exception("Test exception"));

        error.Code.ShouldBe(ErrorInfoProvider.GetErrorCode <Exception>());

        var info = new ErrorInfoProvider().GetInfo(error);

        info.Extensions.ShouldNotBeNull();
        info.Extensions.ShouldContainKey("code");
        info.Extensions["code"].ShouldBe(ErrorInfoProvider.GetErrorCode <Exception>());
        info.Extensions.ShouldContainKey("codes");
        info.Extensions["codes"].ShouldBeAssignableTo <IEnumerable <object> >().ShouldBe(new[] { ErrorInfoProvider.GetErrorCode <Exception>() });
    }
示例#20
0
        public static void SetArrayItemNodes(ExecutionContext context, ArrayExecutionNode parent)
        {
            var listType = (ListGraphType)parent.GraphType;
            var itemType = listType.ResolvedType;

            if (itemType is NonNullGraphType nonNullGraphType)
            {
                itemType = nonNullGraphType.ResolvedType;
            }

            if (!(parent.Result is IEnumerable data))
            {
                var error = new ExecutionError("User error: expected an IEnumerable list though did not find one.");
                throw error;
            }

            var index      = 0;
            var arrayItems = (data is ICollection collection)
                ? new List <ExecutionNode>(collection.Count)
                : new List <ExecutionNode>();

            foreach (var d in data)
            {
                var path = AppendPath(parent.Path, (index++).ToString());

                if (d != null)
                {
                    var node = BuildExecutionNode(parent, itemType, parent.Field, parent.FieldDefinition, path);
                    node.Result = d;

                    if (node is ObjectExecutionNode objectNode)
                    {
                        SetSubFieldNodes(context, objectNode);
                    }

                    arrayItems.Add(node);
                }
                else
                {
                    var valueExecutionNode = new ValueExecutionNode(parent, itemType, parent.Field, parent.FieldDefinition, path)
                    {
                        Result = null
                    };
                    arrayItems.Add(valueExecutionNode);
                }
            }

            parent.Items = arrayItems;
        }
示例#21
0
        private ResolveEventStreamResult GenerateError(
            ResolveEventStreamResult resolveResult,
            Field field,
            ExecutionContext context,
            Exception exc,
            IEnumerable <string> path)
        {
            var error = new ExecutionError("Error trying to resolve {0}.".ToFormat(field.Name), exc);

            error.AddLocation(field, context.Document);
            error.Path = path;
            context.Errors.Add(error);
            resolveResult.Skip = false;
            return(resolveResult);
        }
示例#22
0
 public async Task <TResult> TryAsyncResolve <TResult>(Func <ResolveFieldContext <TSource>, Task <TResult> > resolve, Func <ExecutionErrors, Task <TResult> > error = null)
 {
     try
     {
         return(await resolve(this));
     }
     catch (Exception ex)
     {
         if (error == null)
         {
             var er = new ExecutionError(ex.Message, ex);
             er.AddLocation(FieldAst, Document);
             er.Path = Path;
             Errors.Add(er);
             return(default);
示例#23
0
        /// <inheritdoc/>
        public virtual ErrorInfo GetInfo(ExecutionError executionError)
        {
            if (executionError == null)
            {
                throw new ArgumentNullException(nameof(executionError));
            }

            IDictionary <string, object> extensions = null;

            if (_options.ExposeExtensions)
            {
                var code  = _options.ExposeCode ? executionError.Code : null;
                var codes = _options.ExposeCodes ? GetCodesForError(executionError).ToList() : null;
                if (codes?.Count == 0)
                {
                    codes = null;
                }
                var number = _options.ExposeCode && executionError is ValidationError validationError ? validationError.Number : null;
                var data   = _options.ExposeData && executionError.Data?.Count > 0 ? executionError.Data : null;

                if (code != null || codes != null || data != null)
                {
                    extensions = new Dictionary <string, object>();
                    if (code != null)
                    {
                        extensions.Add("code", code);
                    }
                    if (codes != null)
                    {
                        extensions.Add("codes", codes);
                    }
                    if (number != null)
                    {
                        extensions.Add("number", number);
                    }
                    if (data != null)
                    {
                        extensions.Add("data", data);
                    }
                }
            }

            return(new ErrorInfo
            {
                Message = _options.ExposeExceptionStackTrace ? executionError.ToString() : executionError.Message,
                Extensions = extensions,
            });
        }
示例#24
0
        public void Very_Long_Number_Should_Return_Error_For_Int()
        {
            var query = "{ int }";
            var error = new ExecutionError("Error trying to resolve field 'int'.", new OverflowException());

            error.AddLocation(1, 3);
            error.Path = new object[] { "int" };
            var expected = new ExecutionResult {
                Errors = new ExecutionErrors {
                    error
                },
                Data = new { @int = (object)null }
            };

            AssertQueryIgnoreErrors(query, expected, renderErrors: true, expectedErrorCount: 1);
        }
示例#25
0
        private static ActionResult GetResultForException(ExecutionError error, ControllerBase controller, GqlRequest request)
        {
            var exception = error.GetBaseException();

            if (exception is ValidationError)
            {
                return(null);
            }

            if (exception is UnauthorizedException uex)
            {
                return(controller.StatusCode((int)HttpStatusCode.Forbidden));
            }

            throw new GqlException(exception.Message, exception, request, error.Code);
        }
示例#26
0
        public Task <object> Resolve(
            ResolveFieldContext context,
            FieldMiddlewareDelegate next)
        {
            if (context.FieldDefinition.RequiresAuthorization())
            {
                var err = new ExecutionError($"not authorized to access {context.ParentType.Name} : {context.FieldName}");

                context.Errors.Add(err);
                return(Task.FromResult <object>(null));
            }
            else
            {
                return(next(context));
            }
        }
        public void NotEmpty_ValidationFailed_ReturnsCorrectResult()
        {
            var expectedInvalidProperty = nameof(FakeInstance.Property);
            var expectedErrorMessage    = string.Format(CultureInfo.InvariantCulture, NotEmptyAttribute.ErrorMessageTemplate, expectedInvalidProperty);
            var expectedErrorCodeInfo   = new ErrorCodeInfo(AnnotationErrorCodes.NotEmpty.Code, expectedErrorMessage);
            var expectedExecutionError  = new ExecutionError(expectedErrorCodeInfo, expectedInvalidProperty, expectedErrorMessage);

            var instance = new FakeInstance();
            var context  = new ValidationContext(instance);

            var errors  = new List <ExecutionError>();
            var isValid = CoreValidator.TryValidateObject(instance, context, errors, true);

            isValid.Should().BeFalse();
            errors.Single().Should().BeEquivalentTo(expectedExecutionError);
        }
示例#28
0
        private void interpretError(Context context, ExecutionError e)
        {
            IValue actual        = e.interpret(context, "__test_error__");
            IValue expectedError = error == null ? null : error.interpret(context);

            if (expectedError != null && expectedError.Equals(actual))
            {
                printSuccess(context);
            }
            else
            {
                String actualName   = ((IInstance)actual).GetMemberValue(context, "name", false).ToString();
                String expectedName = error == null ? "SUCCESS" : error.getName();
                printMissingError(context, expectedName, actualName);
            }
        }
示例#29
0
        private static Trace.Error CreateTraceError(ExecutionError executionError)
        {
            var error = new Trace.Error
            {
                Json    = JsonConvert.SerializeObject(executionError),
                Message = executionError.Message
            };

            if (executionError.Locations != null)
            {
                error.Locations.AddRange(executionError.Locations.Select(x => new Trace.Location {
                    Column = (uint)x.Column, Line = (uint)x.Line
                }));
            }
            return(error);
        }
    public void message_and_code()
    {
        var error = new ExecutionError(null)
        {
            Code = "test code"
        };

        var info = new ErrorInfoProvider().GetInfo(error);

        info.Message.ShouldBe(error.Message);
        info.Extensions.ShouldNotBeNull();
        info.Extensions.Count.ShouldBe(2);
        info.Extensions.ShouldContainKeyAndValue("code", "test code");
        info.Extensions.ShouldContainKey("codes");
        info.Extensions["codes"].ShouldBeAssignableTo <IEnumerable <string> >().ShouldBe(new[] { "test code" });
    }
示例#31
0
        public async Task<ResolveFieldResult<object>> ResolveFieldAsync(ExecutionContext context, IObjectGraphType parentType, object source, Fields fields)
        {
            context.CancellationToken.ThrowIfCancellationRequested();

            var resolveResult = new ResolveFieldResult<object>
            {
                Skip = false
            };

            var field = fields.First();

            var fieldDefinition = GetFieldDefinition(context.Schema, parentType, field);
            if (fieldDefinition == null)
            {
                resolveResult.Skip = true;
                return resolveResult;
            }

            var arguments = GetArgumentValues(context.Schema, fieldDefinition.Arguments, field.Arguments, context.Variables);

            try
            {
                var resolveContext = new ResolveFieldContext();
                resolveContext.FieldName = field.Name;
                resolveContext.FieldAst = field;
                resolveContext.FieldDefinition = fieldDefinition;
                resolveContext.ReturnType = fieldDefinition.ResolvedType;
                resolveContext.ParentType = parentType;
                resolveContext.Arguments = arguments;
                resolveContext.Source = source;
                resolveContext.Schema = context.Schema;
                resolveContext.Document = context.Document;
                resolveContext.Fragments = context.Fragments;
                resolveContext.RootValue = context.RootValue;
                resolveContext.UserContext = context.UserContext;
                resolveContext.Operation = context.Operation;
                resolveContext.Variables = context.Variables;
                resolveContext.CancellationToken = context.CancellationToken;
                resolveContext.Metrics = context.Metrics;

                var resolver = fieldDefinition.Resolver ?? new NameFieldResolver();
                var result = resolver.Resolve(resolveContext);

                if (result is Task)
                {
                    var task = result as Task;
                    await task.ConfigureAwait(false);

                    result = task.GetProperyValue("Result");
                }

                resolveResult.Value =
                    await CompleteValueAsync(context, fieldDefinition.ResolvedType, fields, result).ConfigureAwait(false);
                return resolveResult;
            }
            catch (Exception exc)
            {
                var error = new ExecutionError("Error trying to resolve {0}.".ToFormat(field.Name), exc);
                error.AddLocation(field, context.Document);
                context.Errors.Add(error);
                resolveResult.Skip = false;
                return resolveResult;
            }
        }
示例#32
0
        public object GetVariableValue(Document document, ISchema schema, VariableDefinition variable, object input)
        {
            var type = variable.Type.GraphTypeFromType(schema);

            if (IsValidValue(schema, type, input))
            {
                if (input == null)
                {
                    if (variable.DefaultValue != null)
                    {
                        return ValueFromAst(variable.DefaultValue);
                    }
                }
                var coercedValue = CoerceValue(schema, type, input.AstFromValue(schema, type));
                return coercedValue;
            }

            if (input == null)
            {
                var error2 = new ExecutionError("Variable '${0}' of required type '{1}' was not provided.".ToFormat(variable.Name, type.Name ?? variable.Type.FullName()));
                error2.AddLocation(variable, document);
                throw error2;
            }

            var error = new ExecutionError("Variable '${0}' expected value of type '{1}'.".ToFormat(variable.Name, type?.Name ?? variable.Type.FullName()));
            error.AddLocation(variable, document);
            throw error;
        }
示例#33
0
        public async Task<object> CompleteValueAsync(ExecutionContext context, IGraphType fieldType, Fields fields, object result)
        {
            var field = fields != null ? fields.FirstOrDefault() : null;
            var fieldName = field != null ? field.Name : null;

            var nonNullType = fieldType as NonNullGraphType;
            if (nonNullType != null)
            {
                var type = nonNullType.ResolvedType;
                var completed = await CompleteValueAsync(context, type, fields, result).ConfigureAwait(false);
                if (completed == null)
                {
                    var error = new ExecutionError("Cannot return null for non-null type. Field: {0}, Type: {1}!."
                        .ToFormat(fieldName, type.Name));
                    error.AddLocation(field, context.Document);
                    throw error;
                }

                return completed;
            }

            if (result == null)
            {
                return null;
            }

            if (fieldType is ScalarGraphType)
            {
                var scalarType = fieldType as ScalarGraphType;
                var coercedValue = scalarType.Serialize(result);
                return coercedValue;
            }

            if (fieldType is ListGraphType)
            {
                var list = result as IEnumerable;

                if (list == null)
                {
                    var error = new ExecutionError("User error: expected an IEnumerable list though did not find one.");
                    error.AddLocation(field, context.Document);
                    throw error;
                }

                var listType = fieldType as ListGraphType;
                var itemType = listType.ResolvedType;

                var results = await list.MapAsync(async item => await CompleteValueAsync(context, itemType, fields, item).ConfigureAwait(false)).ConfigureAwait(false);

                return results;
            }

            var objectType = fieldType as IObjectGraphType;

            if (fieldType is IAbstractGraphType)
            {
                var abstractType = fieldType as IAbstractGraphType;
                objectType = abstractType.GetObjectType(result);

                if (objectType != null && !abstractType.IsPossibleType(objectType))
                {
                    var error = new ExecutionError(
                        "Runtime Object type \"{0}\" is not a possible type for \"{1}\""
                        .ToFormat(objectType, abstractType));
                    error.AddLocation(field, context.Document);
                    throw error;
                }
            }

            if (objectType == null)
            {
                return null;
            }

            if (objectType.IsTypeOf != null && !objectType.IsTypeOf(result))
            {
                var error = new ExecutionError(
                    "Expected value of type \"{0}\" but got: {1}."
                    .ToFormat(objectType, result));
                error.AddLocation(field, context.Document);
                throw error;
            }

            var subFields = new Dictionary<string, Fields>();
            var visitedFragments = new List<string>();

            fields.Apply(f =>
            {
                subFields = CollectFields(context, objectType, f.SelectionSet, subFields, visitedFragments);
            });

            return await ExecuteFieldsAsync(context, objectType, result, subFields).ConfigureAwait(false);
        }
示例#34
0
        public IObjectGraphType GetOperationRootType(Document document, ISchema schema, Operation operation)
        {
            IObjectGraphType type;

            ExecutionError error;

            switch (operation.OperationType)
            {
                case OperationType.Query:
                    type = schema.Query;
                    break;

                case OperationType.Mutation:
                    type = schema.Mutation;
                    if (type == null)
                    {
                        error = new ExecutionError("Schema is not configured for mutations");
                        error.AddLocation(operation, document);
                        throw error;
                    }
                    break;

                case OperationType.Subscription:
                    type = schema.Subscription;
                    if (type == null)
                    {
                        error = new ExecutionError("Schema is not configured for subscriptions");
                        error.AddLocation(operation, document);
                        throw error;
                    }
                    break;

                default:
                    error = new ExecutionError("Can only execute queries, mutations and subscriptions.");
                    error.AddLocation(operation, document);
                    throw error;
            }

            return type;
        }
示例#35
0
        public async Task<ResolveFieldResult<object>> ResolveFieldAsync(ExecutionContext context, ObjectGraphType parentType, object source, Fields fields)
        {
            context.CancellationToken.ThrowIfCancellationRequested();

            var resolveResult = new ResolveFieldResult<object>
            {
                Skip = false
            };

            var field = fields.First();

            var fieldDefinition = GetFieldDefinition(context.Schema, parentType, field);
            if (fieldDefinition == null)
            {
                resolveResult.Skip = true;
                return resolveResult;
            }

            var arguments = GetArgumentValues(context.Schema, fieldDefinition.Arguments, field.Arguments, context.Variables);

            Func<ResolveFieldContext, object> defaultResolve =
                ctx => ctx.Source != null
                    ? GetProperyValue(ctx.Source, ctx.FieldAst.Name)
                    : null;

            try
            {
                var resolveContext = new ResolveFieldContext();
                resolveContext.FieldName = field.Name;
                resolveContext.FieldAst = field;
                resolveContext.FieldDefinition = fieldDefinition;
                resolveContext.ReturnType = context.Schema.FindType(fieldDefinition.Type);
                resolveContext.ParentType = parentType;
                resolveContext.Arguments = arguments;
                resolveContext.Source = source;
                resolveContext.Schema = context.Schema;
                resolveContext.Fragments = context.Fragments;
                resolveContext.RootValue = context.RootValue;
                resolveContext.Operation = context.Operation;
                resolveContext.Variables = context.Variables;
                resolveContext.CancellationToken = context.CancellationToken;
                var resolve = fieldDefinition.Resolve ?? defaultResolve;
                var result = resolve(resolveContext);

                if(result is Task)
                {
                    var task = result as Task;
                    await task.ConfigureAwait(false);

                    result = GetProperyValue(task, "Result");
                }

                if (parentType is __Field && result is Type)
                {
                    result = context.Schema.FindType(result as Type);
                }

                resolveResult.Value = await CompleteValueAsync(context, context.Schema.FindType(fieldDefinition.Type), fields, result).ConfigureAwait(false);
                return resolveResult;
            }
            catch (Exception exc)
            {
                var error = new ExecutionError("Error trying to resolve {0}.".ToFormat(field.Name), exc);
                error.AddLocation(field.SourceLocation.Line, field.SourceLocation.Column);
                context.Errors.Add(error);
                resolveResult.Skip = false;
                return resolveResult;
            }
        }
 private ResolveFieldResult<object> GenerateError(ResolveFieldResult<object> resolveResult, Field field, ExecutionContext context, Exception exc)
 {
     var error = new ExecutionError("Error trying to resolve {0}.".ToFormat(field.Name), exc);
     error.AddLocation(field, context.Document);
     context.Errors.Add(error);
     resolveResult.Skip = false;
     return resolveResult;
 }