/// <summary> /// Correctly renders the Graphql result for returning to the user /// </summary> /// <param name="result">The graphql execution result</param> /// <returns>The graphql execution result with better formatting</returns> private ExecutionResult RenderResult(ExecutionResult result) { if (result.Errors?.Count > 0) { var newEx = new ExecutionErrors(); foreach (var error in result.Errors) { var ex = error.InnerException; if (ex is PostgresException pgException) { if (string.IsNullOrWhiteSpace(pgException.MessageText)) { newEx.Add(error); } else { newEx.Add(new ExecutionError(pgException.MessageText)); } } else { newEx.Add(error); } _logger.LogError( "Graphql error message: {Error}\nException: {Exception}", error.Message, ex?.ToString()); } result.Errors = newEx; Response.StatusCode = (int)HttpStatusCode.BadRequest; } return(result); }
public UmbracoGraphQLContext(Uri requestUri, ApplicationContext applicationContext, UmbracoContext umbracoContext, GraphQLServerOptions options, string accessToken, out ExecutionErrors errors) { errors = new ExecutionErrors(); RequestUri = requestUri; ApplicationContext = applicationContext ?? throw new ArgumentNullException(nameof(applicationContext)); Options = options ?? throw new ArgumentNullException(nameof(options)); UmbracoContext = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext)); Claims = new List <string>(); // no claims is the default var db = ApplicationContext.Current.DatabaseContext.Database; Account account = null; // TODO: Pete - need to cache these authentication look ups for speed // Which permissions should we use? if (!String.IsNullOrEmpty(accessToken)) { var accessTokenGuid = new Guid(); if (Guid.TryParse(accessToken, out accessTokenGuid)) { account = db.SingleOrDefault <Account>("WHERE AccessToken = @0", accessToken); } else { errors.Add(new ExecutionError("Malformed Access Token passed in, please check it")); } } if (account == null) { // Fall back to the default permissions //errors.Add(new ExecutionError("Unknown Access Token, please check, falling back to Default permissions")); account = db.SingleOrDefault <Account>("WHERE AccessToken = @0", defaultAccessToken); } if (account == null) { errors.Add(new ExecutionError("No default permissions found, check the account settings in the GraphQL section of the CMS")); } else { if (account.IsEnabled) { var settings = db.Query <AccountSettings>("WHERE AccountId = @0", account.Id); if (settings != null) { foreach (var setting in settings) { // Do we check that we actually still have the doctypes active? Claims.Add(setting.PermissionClaimHash); } } } else { errors.Add(new ExecutionError("Passed in account is deactivated")); } } }
public GraphQLFixture() { Schema = Substitute.For <ISchema>(); Doc = Substitute.For <IDocumentExecuter>(); Errors = new ExecutionErrors(); Errors.Add(new ExecutionError("wrong")); }
internal async Task <ExecutionResult> Execute( object rootObject, string query, string operationName, Inputs inputs, IUserContext userContext, bool enableValidation = true, bool enableProfiling = false, IEnumerable <IValidationRule> rules = null, CancellationToken cancellationToken = default(CancellationToken)) { if (!enableValidation) { rules = new[] { new NoopValidationRule() }; } var configuration = new ExecutionOptions { Schema = _schema, Root = rootObject, Query = query, OperationName = operationName, Inputs = inputs, UserContext = userContext, ValidationRules = rules, CancellationToken = cancellationToken, }; if (userContext is IDataLoaderContextProvider) { configuration.Listeners.Add(new DataLoaderListener()); } if (enableProfiling) { configuration.FieldMiddleware.Use <InstrumentFieldsMiddleware>(); } var result = await _documentExecutor.ExecuteAsync(configuration).ConfigureAwait(false); if (result.Errors != null) { var errors = new ExecutionErrors(); foreach (var executionError in result.Errors) { var exception = new FieldResolutionException(executionError); var error = new ExecutionError(exception.Message, exception); error.SetCode(exception.InnerException ?? exception); foreach (var location in executionError.Locations ?? new ErrorLocation[0]) { error.AddLocation(location.Line, location.Column); } error.Path.AddRange(executionError.Path); errors.Add(error); } result.Errors = errors; } return(result); }
public static void AddGraphQLExceptions(this ExecutionErrors errors, Exception exception) { switch (exception) { case InvalidArgumentException invalidArgumentEx: errors.Add(new ExecutionError(invalidArgumentEx.Body)); break; case NotFoundException notFoundEx: errors.Add(new ExecutionError(notFoundEx.Body)); break; case BaseException baseEx: errors.AddRange(((List <ValidationFailure>)baseEx.Body).Select(validationFailure => new ExecutionError(validationFailure.ErrorMessage))); break; default: errors.Add(new ExecutionError(exception.Message)); break; } }
public void should_add_extension_object_when_exception_is_thrown_with_error_code() { string query = "{ firstSync }"; string code = "FIRST"; var errors = new ExecutionErrors(); var error = new ValidationError(query, code, "Error trying to resolve field 'firstSync'.", new SystemException("Just inner exception 1", new DllNotFoundException("just inner exception 2"))); error.AddLocation(1, 3); error.Path = new[] { "firstSync" }; errors.Add(error); var expectedResult = @"{ ""firstSync"": null}"; AssertQuery(query, CreateQueryResult(expectedResult, errors), null, null); }
public void use_undefined_fragment() { var query = @" query someDroids { r2d2: droid(id: ""3"") { ...unknown_fragment name } } "; var errors = new ExecutionErrors(); var error = new ExecutionError(@"Unknown fragment ""unknown_fragment""."); error.AddLocation(4, 25); errors.Add(error); AssertQuery(query, CreateQueryResult(null, errors), null, null); }
public async Task should_not_add_extension_object_when_exception_is_thrown_without_error_code() { string query = "{ uncodedSync }"; var result = await Executer.ExecuteAsync(_ => { _.Schema = Schema; _.Query = query; }); var errors = new ExecutionErrors(); var error = new ExecutionError("Error trying to resolve uncodedSync."); error.AddLocation(1, 3); error.Path = new[] { "uncodedSync" }; errors.Add(error); var expectedResult = "{uncodedSync: null}"; AssertQuery(query, CreateQueryResult(expectedResult, errors), null, null); }
public void use_undefined_fragment() { var query = @" query someDroids { r2d2: droid(id: ""3"") { ...unknown_fragment name } } "; var errors = new ExecutionErrors(); var error = new ValidationError(query, KnownFragmentNamesError.NUMBER, @"Unknown fragment ""unknown_fragment"".") { Code = "KNOWN_FRAGMENT_NAMES" }; error.AddLocation(4, 25); errors.Add(error); AssertQuery(query, CreateQueryResult(null, errors), null, null); }
public async Task should_add_extension_object_when_exception_is_thrown_with_error_code() { string query = "{ firstSync }"; string code = "FIRST"; var result = await Executer.ExecuteAsync(_ => { _.Schema = Schema; _.Query = query; }); var errors = new ExecutionErrors(); var error = new ValidationError(query, code, "Error trying to resolve firstSync.", new SystemException("Just inner exception 1", new DllNotFoundException("just inner exception 2"))); error.AddLocation(1, 3); error.Path = new[] { "firstSync" }; errors.Add(error); var expectedResult = "{firstSync: null}"; AssertQuery(query, CreateQueryResult(expectedResult, errors), null, null); }
internal async Task <ExecutionResult> Execute( object rootObject, string query, string operationName, Inputs inputs, IUserContext userContext, IDependencyInjector dependencyInjector, ComplexityConfiguration complexityConfiguration, bool enableValidation = true, bool enableProfiling = false, IEnumerable <IValidationRule> rules = null, CancellationToken cancellationToken = default(CancellationToken)) { if (!enableValidation) { rules = new[] { new NoopValidationRule() }; } var configuration = new ExecutionOptions { Schema = _schema, Root = rootObject, Query = query, OperationName = operationName, Inputs = inputs, UserContext = UserContextWrapper.Create(userContext, dependencyInjector ?? new WrappedDependencyInjector(_constructor.TypeResolutionDelegate)), ValidationRules = rules != null && rules.Any() ? rules : null, ComplexityConfiguration = complexityConfiguration, CancellationToken = cancellationToken, }; if (userContext is IDataLoaderContextProvider) { configuration.Listeners.Add(new DataLoaderListener()); } if (enableProfiling) { configuration.FieldMiddleware.Use <InstrumentFieldsMiddleware>(); } foreach (var middleware in _middleware) { configuration.FieldMiddleware.Use(middleware); } var result = await _documentExecutor.ExecuteAsync(configuration).ConfigureAwait(false); if (result.Errors != null) { var errors = new ExecutionErrors(); foreach (var executionError in result.Errors) { var exception = new FieldResolutionException(executionError); var error = new ExecutionError(exception.Message, exception); foreach (var location in executionError.Locations ?? new ErrorLocation[0]) { error.AddLocation(location.Line, location.Column); } error.Path = executionError.Path; errors.Add(error); } result.Errors = errors; } return(result); }