private void writeErrors(ExecutionErrors errors, JsonWriter writer, JsonSerializer serializer) { if (errors == null || errors.Count == 0) { return; } writer.WritePropertyName("errors"); writer.WriteStartArray(); errors.Apply(error => { writer.WriteStartObject(); writer.WritePropertyName("message"); serializer.Serialize(writer, error.Message); if (error.Locations != null) { writer.WritePropertyName("locations"); serializer.Serialize(writer, error.Locations); } writer.WriteEndObject(); }); writer.WriteEndArray(); }
/// <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 GraphQLFixture() { Schema = Substitute.For <ISchema>(); Doc = Substitute.For <IDocumentExecuter>(); Errors = new ExecutionErrors(); Errors.Add(new ExecutionError("wrong")); }
private void AssertResult(string query, string expected, Data data, IReadOnlyList <ExecutionError> errors) { ExecutionResult result = AssertQueryWithErrors( query, expected, root: data, expectedErrorCount: errors.Count); ExecutionErrors actualErrors = result.Errors; if (errors.Count == 0) { actualErrors.ShouldBeNull(); } else { actualErrors.Count.ShouldBe(errors.Count); for (var i = 0; i < errors.Count; i++) { ExecutionError actualError = actualErrors[i]; ExecutionError expectedError = errors[i]; actualError.Message.ShouldBe(expectedError.Message); actualError.Path.ShouldBe(expectedError.Path); } } }
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")); } } }
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 SysMessageLog(IUserModel user, string logPath = SystemCP.LogDefaultPath, string logFileName = SystemCP.LogDefaultFileName) { Errors = new ExecutionErrors(); LogPath = logPath; LogFileName = logFileName; Prefix = string.Empty; User = user ?? SystemOperator.SysOperator; }
private static void WriteErrors(Utf8JsonWriter writer, ExecutionErrors errors, IErrorInfoProvider errorInfoProvider, JsonSerializerOptions options) { if (errors == null || errors.Count == 0) { return; } writer.WritePropertyName("errors"); writer.WriteStartArray(); foreach (var error in errors) { var info = errorInfoProvider.GetInfo(error); writer.WriteStartObject(); writer.WritePropertyName("message"); JsonSerializer.Serialize(writer, info.Message, options); if (error.Locations != null) { writer.WritePropertyName("locations"); writer.WriteStartArray(); foreach (var location in error.Locations) { writer.WriteStartObject(); writer.WritePropertyName("line"); JsonSerializer.Serialize(writer, location.Line, options); writer.WritePropertyName("column"); JsonSerializer.Serialize(writer, location.Column, options); writer.WriteEndObject(); } writer.WriteEndArray(); } if (error.Path != null && error.Path.Any()) { writer.WritePropertyName("path"); JsonSerializer.Serialize(writer, error.Path, options); } if (info.Extensions?.Count > 0) { writer.WritePropertyName("extensions"); JsonSerializer.Serialize(writer, info.Extensions, options); } writer.WriteEndObject(); } writer.WriteEndArray(); }
private void WriteErrors(ExecutionErrors errors, JsonWriter writer, JsonSerializer serializer) { if (errors == null || errors.Count == 0) { return; } writer.WritePropertyName("errors"); writer.WriteStartArray(); foreach (var error in errors) { var info = _errorInfoProvider.GetInfo(error); writer.WriteStartObject(); writer.WritePropertyName("message"); serializer.Serialize(writer, info.Message); if (error.Locations != null) { writer.WritePropertyName("locations"); writer.WriteStartArray(); error.Locations.Apply(location => { writer.WriteStartObject(); writer.WritePropertyName("line"); serializer.Serialize(writer, location.Line); writer.WritePropertyName("column"); serializer.Serialize(writer, location.Column); writer.WriteEndObject(); }); writer.WriteEndArray(); } if (error.Path != null && error.Path.Any()) { writer.WritePropertyName("path"); serializer.Serialize(writer, error.Path); } if (info.Extensions?.Count > 0) { writer.WritePropertyName("extensions"); serializer.Serialize(writer, info.Extensions); } writer.WriteEndObject(); } writer.WriteEndArray(); }
private void writeErrors(ExecutionErrors errors, JsonWriter writer, JsonSerializer serializer, bool exposeExceptions) { if (errors == null || !errors.Any()) { return; } writer.WritePropertyName("errors"); writer.WriteStartArray(); errors.Apply(error => { writer.WriteStartObject(); writer.WritePropertyName("message"); // check if return StackTrace, including all inner exceptions serializer.Serialize(writer, exposeExceptions ? error.ToString() : error.Message); if (error.Locations != null) { writer.WritePropertyName("locations"); writer.WriteStartArray(); error.Locations.Apply(location => { writer.WriteStartObject(); writer.WritePropertyName("line"); serializer.Serialize(writer, location.Line); writer.WritePropertyName("column"); serializer.Serialize(writer, location.Column); writer.WriteEndObject(); }); writer.WriteEndArray(); } if (error.Path != null && error.Path.Any()) { writer.WritePropertyName("path"); serializer.Serialize(writer, error.Path); } if (error is ValidationError ve) { writer.WritePropertyName("errorCode"); serializer.Serialize(writer, ve.ErrorCode); } writer.WriteEndObject(); }); writer.WriteEndArray(); }
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); });
private ExecutionResult CreateQueryResult(string result, ExecutionErrors errors = null) { object data = null; if (!string.IsNullOrWhiteSpace(result)) { data = DeserializeObject(result); } return(new ExecutionResult { Data = data, Errors = errors }); }
protected ExecutionResult CreateQueryResult(string result, ExecutionErrors errors = null) { object data = null; if (!string.IsNullOrWhiteSpace(result)) { data = JObject.Parse(result); } return(new ExecutionResult { Data = data, Errors = errors }); }
public ExecutionResult Execute() { var context = new ExecutionContext { Document = Document, Schema = Schema, RootValue = null, UserContext = new Dictionary <string, object>(), Operation = Operation, Variables = Variables, Errors = new ExecutionErrors(), Extensions = new Dictionary <string, object>(), CancellationToken = default,
private static void WriteErrors(Utf8JsonWriter writer, ExecutionErrors errors, bool exposeExceptions, JsonSerializerOptions options) { if (errors == null || errors.Count == 0) { return; } writer.WritePropertyName("errors"); writer.WriteStartArray(); errors.Apply(error => { writer.WriteStartObject(); writer.WritePropertyName("message"); // Check if return StackTrace, including all inner exceptions JsonSerializer.Serialize(writer, exposeExceptions ? error.ToString() : error.Message, options); if (error.Locations != null) { writer.WritePropertyName("locations"); writer.WriteStartArray(); error.Locations.Apply(location => { writer.WriteStartObject(); writer.WritePropertyName("line"); JsonSerializer.Serialize(writer, location.Line, options); writer.WritePropertyName("column"); JsonSerializer.Serialize(writer, location.Column, options); writer.WriteEndObject(); }); writer.WriteEndArray(); } if (error.Path != null && error.Path.Any()) { writer.WritePropertyName("path"); JsonSerializer.Serialize(writer, error.Path, options); } WriteErrorExtensions(writer, error, options); writer.WriteEndObject(); }); writer.WriteEndArray(); }
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 async Task <bool> Execute() { if (ValidationErrors.Any()) { return(false); } messages = _repository.GetAll().ToList(); if (!messages.Any()) { ExecutionErrors.AddError("", new List <string>() { "Could Not Retreive Message" }); return(false); } return(true); }
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 void async_field_with_errors() { var error = new ExecutionError("Error trying to resolve testasync."); error.AddLocation(1, 3); var errors = new ExecutionErrors { error }; AssertQueryIgnoreErrors( "{ testasync }", CreateQueryResult(@"{ ""testasync"": null }", errors), expectedErrorCount: 1, renderErrors: true); }
public void async_field_with_errors() { var error = new UnhandledError("Error trying to resolve field 'testasync'.", new Exception()); error.AddLocation(new Location(1, 3)); error.Path = new[] { "testasync" }; var errors = new ExecutionErrors { error }; AssertQueryIgnoreErrors( "{ testasync }", CreateQueryResult(@"{ ""testasync"": null }", errors), expectedErrorCount: 1, renderErrors: true); }
public static void ToException(this ExecutionErrors errors) { var error = new BaseApplicationException(ErrorCodes.MultipleErrors, ErrorMessages.MultipleErrors, HttpStatusCode.BadRequest); if (errors != null) { foreach (var executionError in errors) { if (executionError.InnerException != null) { var info = executionError.InnerException.ToErrorInfo(); if (info != null) { error.Infos.Add(info); } } } } throw error; }
public ResolveFieldContext(ResolveFieldContext context) { Source = (TSource)context.Source; FieldName = context.FieldName; FieldAst = context.FieldAst; FieldDefinition = context.FieldDefinition; ReturnType = context.ReturnType; ParentType = context.ParentType; Arguments = context.Arguments; Schema = context.Schema; Document = context.Document; Fragments = context.Fragments; RootValue = context.RootValue; UserContext = context.UserContext; Operation = context.Operation; Variables = context.Variables; CancellationToken = context.CancellationToken; Metrics = context.Metrics; Errors = context.Errors; }
public ApiErrorResp(ExecutionErrors executionErrors) { List <string> _errorMessages = new List <string>(); foreach (var executionError in executionErrors) { if (executionError?.InnerException?.Message != null) { if (executionError.InnerException.Message != Utilities.EnumHelper.GetDescription(Utilities.EnumHelper.InputValidationError.InputValidationError)) { _errorMessages.Add(executionError.InnerException.Message); } } else { _errorMessages.Add(executionError.Message); } } Errors = _errorMessages; }
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 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); }
private void AssertResult(string query, string expected, Data data, IReadOnlyList <ExecutionError> errors, bool executed = true) { ExecutionResult result = AssertQueryWithErrors( query, expected, root: data, expectedErrorCount: errors.Count, executed: executed); ExecutionErrors actualErrors = result.Errors; if (errors.Count == 0) { actualErrors.ShouldBeNull(); } else { actualErrors.Count.ShouldBe(errors.Count); for (var i = 0; i < errors.Count; i++) { ExecutionError actualError = actualErrors[i]; ExecutionError expectedError = errors[i]; actualError.Message.ShouldBe(expectedError.Message); actualError.Path.ShouldBe(expectedError.Path); if (expectedError.InnerException == null) { actualError.InnerException.ShouldBeNull(); } else { actualError.InnerException.ShouldNotBeNull(); actualError.InnerException.ShouldBeOfType(expectedError.InnerException.GetType()); actualError.InnerException.Message.ShouldBe(expectedError.InnerException.Message); } } } }
private void WriteErrors(Utf8JsonWriter writer, ExecutionErrors errors, JsonSerializerOptions options, bool exposeExceptions) { writer.WritePropertyName(nameof(errors)); writer.WriteStartArray(); foreach (var error in errors) { writer.WriteStartObject(); writer.WriteString("message", exposeExceptions ? error.ToString() : error.Message); if (error.Locations != null) { writer.WritePropertyName("locations"); writer.WriteStartArray(); foreach (var location in error.Locations) { writer.WriteStartObject(); writer.WritePropertyName("line"); writer.WriteNumberValue(location.Line); writer.WritePropertyName("column"); writer.WriteNumberValue(location.Column); writer.WriteEndObject(); } writer.WriteEndArray(); } if (error.Path != null && error.Path.Any()) { writer.WritePropertyName("path"); JsonSerializer.Serialize(writer, error.Path, options); } WriteErrorExtensions(writer, error, options); writer.WriteEndObject(); } writer.WriteEndArray(); }
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); }
public ExecutionContext() { Fragments = new Fragments(); Errors = new ExecutionErrors(); }
public override async Task Invoke(IOwinContext context) { try { var schema = _applicationContext.ApplicationCache.RuntimeCache.GetCacheItem <UmbracoSchema>( "Our.Umbraco.GraphQL::Schema", () => new UmbracoSchema( _applicationContext.Services.ContentTypeService, _applicationContext.Services.MemberTypeService, _options ) ); if (false == context.Request.Path.HasValue) { var request = context.Get <GraphQLRequest>("Our.Umbraco.GraphQL::Request"); switch (context.Request.Method) { case "POST": if (request == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("POST body missing."); return; } break; default: context.Response.StatusCode = 405; await context.Response.WriteAsync("Server supports only POST requests."); return; } IEnumerable <Task <ExecutionResult> > requests = request.Select(async requestParams => { string query = requestParams.Query; string operationName = requestParams.OperationName; string accessToken = context.Request.Query["accessToken"]; Inputs variables = requestParams.Variables; var validationRules = new List <IValidationRule> { new RequiresAuthValidationRule() }; var start = DateTime.Now; MiniProfiler.Start(); var errors = new ExecutionErrors(); var result = await _documentExecutor .ExecuteAsync(x => { x.CancellationToken = context.Request.CallCancelled; //x.ComplexityConfiguration = new ComplexityConfiguration(); x.ExposeExceptions = _options.Debug; if (_options.EnableMetrics) { x.EnableMetrics = true; x.FieldMiddleware.Use <InstrumentFieldsMiddleware>(); x.FieldMiddleware.Use <MiniProfilerFieldsMiddleware>(); } x.FieldNameConverter = new DefaultFieldNameConverter(); x.Inputs = variables; x.OperationName = operationName; x.Query = query; //x.Root = x.Schema = schema; x.UserContext = new UmbracoGraphQLContext( context.Request.Uri, _applicationContext, UmbracoContext.Current, _options, accessToken, out errors ); x.ValidationRules = validationRules; }); // Save any of our errors reported by our authentication stuff in UserContext if (errors.Any()) { if (result.Errors != null) { result.Errors.Concat(errors); } else { result.Errors = errors; } } if (_options.EnableMetrics && result.Errors == null) { result.EnrichWithApolloTracing(start); if (result.Extensions == null) { result.Extensions = new Dictionary <string, object>(); } result.Extensions["miniProfiler"] = JObject.FromObject(MiniProfiler.Current, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } MiniProfiler.Stop(); return(result); }); var responses = await Task.WhenAll(requests); context.Response.ContentType = "application/json"; if (false == request.IsBatched) { var response = _documentWriter.Write(responses[0]); await context.Response.WriteAsync(response); } else { var response = _documentWriter.Write(responses); await context.Response.WriteAsync(response); } } else if (context.Request.Path.ToString() == "/schema") { using (var schemaPrinter = new SchemaPrinter(schema)) { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync(schemaPrinter.Print()); } } } catch (Exception ex) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = 500; if (_options.Debug) { await context.Response.WriteAsync(ex.ToString()); } else { await context.Response.WriteAsync("Internal server error"); } } }
public ValidationResult() { Errors = new ExecutionErrors(); }