/// <summary> /// Extracts error details from an <see cref="ODataError"/>. /// </summary> /// <param name="error">The ODataError instance to extract the error details from.</param> /// <param name="code">A data service-defined string which serves as a substatus to the HTTP response code.</param> /// <param name="message">A human readable message describing the error.</param> /// <param name="messageLanguage">The language identifier representing the language the error message is in.</param> internal static void GetErrorDetails(ODataError error, out string code, out string message, out string messageLanguage) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(error != null, "error != null"); code = error.ErrorCode ?? string.Empty; message = error.Message ?? string.Empty; messageLanguage = error.MessageLanguage ?? ODataConstants.ODataErrorMessageDefaultLanguage; }
public void WriteTopLevelErrorUsesProvidedErrorCode() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError { ErrorCode = "Error Code" }; serializer.WriteTopLevelError(error, false); }); result.Should().Contain("\"code\":\"Error Code\""); }
public void WriteTopLevelErrorUsesProvidedMessage() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError { Message = "error message text" }; serializer.WriteTopLevelError(error, false); }); result.Should().Contain("\"message\":\"error message text\""); }
public void WriteTopLevelErrorUsesProvidedTarget() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError { Target = "error target text" }; serializer.WriteTopLevelError(error, includeDebugInformation: false); }); result.Should().Contain("\"target\":\"error target text\""); }
/// <summary> /// Write an error message. /// </summary> /// <param name="jsonWriter">The JSON writer to write the error to.</param> /// <param name="error">The error instance to write.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> /// <param name="maxInnerErrorDepth">The maximumum number of nested inner errors to allow.</param> internal static void WriteError(JsonWriter jsonWriter, ODataError error, bool includeDebugInformation, int maxInnerErrorDepth) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(error != null, "error != null"); string code, message, messageLanguage; ErrorUtils.GetErrorDetails(error, out code, out message, out messageLanguage); ODataInnerError innerError = includeDebugInformation ? error.InnerError : null; ODataJsonWriterUtils.WriteError(jsonWriter, code, message, messageLanguage, innerError, maxInnerErrorDepth); }
/// <summary> /// Write an error message. /// </summary> /// <param name="jsonWriter">The JSON writer to write the error.</param> /// <param name="writeInstanceAnnotationsDelegate">Action to write the instance annotations.</param> /// <param name="error">The error instance to write.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> /// <param name="maxInnerErrorDepth">The maximum number of nested inner errors to allow.</param> /// <param name="writingJsonLight">true if we're writing JSON lite, false if we're writing verbose JSON.</param> internal static void WriteError(IJsonWriter jsonWriter, Action<IEnumerable<ODataInstanceAnnotation>> writeInstanceAnnotationsDelegate, ODataError error, bool includeDebugInformation, int maxInnerErrorDepth, bool writingJsonLight) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(error != null, "error != null"); string code, message; ErrorUtils.GetErrorDetails(error, out code, out message); ODataInnerError innerError = includeDebugInformation ? error.InnerError : null; WriteError(jsonWriter, code, message, innerError, error.GetInstanceAnnotations(), writeInstanceAnnotationsDelegate, maxInnerErrorDepth, writingJsonLight); }
public void WriteError_WritesTargetAndDetails() { var error = new ODataError { Target = "any target", Details = new[] { new ODataErrorDetail { ErrorCode = "500", Target = "any target", Message = "any msg" } } }; ODataJsonWriterUtils.WriteError( jsonWriter, enumerable => { }, error, includeDebugInformation: false, maxInnerErrorDepth: 0, writingJsonLight: false); var result = stringWriter.GetStringBuilder().ToString(); result.Should().Be(@"{""error"":{""code"":"""",""message"":"""",""target"":""any target"","+ @"""details"":[{""code"":""500"",""target"":""any target"",""message"":""any msg""}]}}"); }
public void ODataErrorSerializer_Works() { // Arrange ODataErrorSerializer serializer = new ODataErrorSerializer(); MemoryStream stream = new MemoryStream(); IODataResponseMessage message = new ODataMessageWrapper(stream); ODataError error = new ODataError { Message = "Error!!!" }; ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); settings.SetContentType(ODataFormat.Json); ODataMessageWriter writer = new ODataMessageWriter(message, settings); // Act serializer.WriteObject(error, typeof(ODataError), writer, new ODataSerializerContext()); stream.Seek(0, SeekOrigin.Begin); string result = new StreamReader(stream).ReadToEnd(); // Assert Assert.Equal("{\"error\":{\"code\":\"\",\"message\":\"Error!!!\"}}", result); }
public void WriteTopLevelErrorWithCollectionOfResourceInstanceAnnotation() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError(); var instanceAnnotations = new Collection <ODataInstanceAnnotation>(); var collection = new ODataCollectionValue { TypeName = "Collection(ns.ErrorDetails)", Items = new[] { new ODataResourceValue(), new ODataResourceValue { TypeName = "ns.ErrorDetails" } } }; ODataInstanceAnnotation annotation = new ODataInstanceAnnotation("sample.collection", collection); instanceAnnotations.Add(annotation); error.InstanceAnnotations = instanceAnnotations; serializer.WriteTopLevelError(error, false); }); Assert.Contains("\"[email protected]\":\"#Collection(ns.ErrorDetails)\",\"@sample.collection\":[{},{}]", result); }
/// <summary> /// Asynchronously read a top-level error. /// </summary> /// <returns> /// A task that represents the asynchronous read operation. /// The value of the TResult parameter contains an <see cref="ODataError"/> representing the read error. /// </returns> /// <remarks> /// Pre-Condition: JsonNodeType.Property - The first property of the top level object. /// JsonNodeType.EndObject - If there are no properties in the top level object. /// any - Will throw if anything else. /// Post-Condition: JsonNodeType.EndOfInput /// </remarks> private async Task <ODataError> ReadTopLevelErrorImplementationAsync() { ODataError error = null; while (this.JsonReader.NodeType == JsonNodeType.Property) { string propertyName = await this.JsonReader.ReadPropertyNameAsync() .ConfigureAwait(false); if (!string.Equals(JsonLightConstants.ODataErrorPropertyName, propertyName, StringComparison.Ordinal)) { // We only allow a single 'error' property for a top-level error object throw new ODataException(Strings.ODataJsonErrorDeserializer_TopLevelErrorWithInvalidProperty(propertyName)); } if (error != null) { throw new ODataException(Strings.ODataJsonReaderUtils_MultipleErrorPropertiesWithSameName(JsonLightConstants.ODataErrorPropertyName)); } error = new ODataError(); await this.ReadODataErrorObjectAsync(error) .ConfigureAwait(false); } // Read the end of the error object await this.JsonReader.ReadEndObjectAsync() .ConfigureAwait(false); // Read the end of the response. await this.ReadPayloadEndAsync(isReadingNestedPayload : false) .ConfigureAwait(false); Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: JsonNodeType.EndOfInput"); return(error); }
internal ODataError ReadTopLevelError() { ODataError error2; try { base.XmlReader.DisableInStreamErrorDetection = true; base.ReadPayloadStart(); if (!base.XmlReader.NamespaceEquals(base.XmlReader.ODataMetadataNamespace) || !base.XmlReader.LocalNameEquals(base.XmlReader.ODataErrorElementName)) { throw new ODataErrorException(Strings.ODataAtomErrorDeserializer_InvalidRootElement(base.XmlReader.Name, base.XmlReader.NamespaceURI)); } ODataError error = ReadErrorElement(base.XmlReader, base.MessageReaderSettings.MessageQuotas.MaxNestingDepth); base.XmlReader.Read(); base.ReadPayloadEnd(); error2 = error; } finally { base.XmlReader.DisableInStreamErrorDetection = false; } return(error2); }
public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerWriteContext writeContext) { if (graph == null) { throw Error.ArgumentNull("graph"); } if (messageWriter == null) { throw Error.ArgumentNull("messageWriter"); } ODataError odataError = graph as ODataError; if (odataError == null) { throw Error.InvalidOperation(SRResources.ErrorTypeMustBeODataError, graph.GetType().FullName); } bool includeDebugInformation = odataError.InnerError != null; messageWriter.WriteError(odataError, includeDebugInformation); }
public void WriteError_WritesTargetAndDetails() { var error = new ODataError { Target = "any target", Details = new[] { new ODataErrorDetail { ErrorCode = "500", Target = "any target", Message = "any msg" } } }; ODataJsonWriterUtils.WriteError( jsonWriter, enumerable => { }, error, includeDebugInformation: false, maxInnerErrorDepth: 0, writingJsonLight: false); var result = stringWriter.GetStringBuilder().ToString(); result.Should().Be(@"{""error"":{""code"":"""",""message"":"""",""target"":""any target""," + @"""details"":[{""code"":""500"",""target"":""any target"",""message"":""any msg""}]}}"); }
public void WriteError_InnerErrorWithEmptyStringProperties() { var error = new ODataError { Target = "any target", Details = new[] { new ODataErrorDetail { ErrorCode = "500", Target = "any target", Message = "any msg" } }, InnerError = new ODataInnerError() { Message = "The other properties on the inner error object should serialize as empty strings because of using this constructor." } }; ODataJsonWriterUtils.WriteError( jsonWriter, enumerable => { }, error, includeDebugInformation: true, maxInnerErrorDepth: 5, writingJsonLight: false); var result = stringWriter.GetStringBuilder().ToString(); Assert.Equal("{\"error\":" + "{\"code\":\"\"," + "\"message\":\"\"," + "\"target\":\"any target\"," + "\"details\":[{\"code\":\"500\",\"target\":\"any target\",\"message\":\"any msg\"}]," + "\"innererror\":{" + "\"message\":\"The other properties on the inner error object should serialize as empty strings because of using this constructor.\"," + "\"type\":\"\"," + "\"stacktrace\":\"\"" + "}" + "}" + "}", result); }
public override void OnException(HttpActionExecutedContext context) { if (context.Exception != null) { HttpStatusCode code; ODataError report = null; if (context.Exception is HttpResponseException) { return; } else if (context.Exception is ServiceException) { var e = (ServiceException)context.Exception.GetLastInnerException(); report = e.Error; code = e.StatusCode; } else if (context.Exception is ModelStateException) { var e = new ServiceException((ModelStateException)context.Exception); report = e.Error; code = e.StatusCode; } else { report = CommunicationErrors.InternalServerError; report.InnerError = new ODataInnerError(context.Exception.GetLastInnerException()); code = HttpStatusCode.InternalServerError; } LogException(context, code, report); context.Exception = new HttpResponseException(context.Request.CreateResponse(code, report)); } }
public void CreateODataError_Creates_BasicODataError_WithoutModelStateDictionary() { // Arrange & Act & Assert ModelStateDictionary modelState = new ModelStateDictionary(); modelState.AddModelError("key3", "Test Error 3"); SerializableError innerSerializableError = new SerializableError(modelState); SerializableError serializableError = new SerializableError(); serializableError["key1"] = "Test Error 1"; serializableError["key2"] = "Test Error 2"; serializableError["ModelState"] = innerSerializableError; // Act ODataError error = SerializableErrorExtensions.CreateODataError(serializableError); // Assert Assert.NotNull(error); Assert.Equal("key1:\r\nTest Error 1\r\n\r\nkey2:\r\nTest Error 2", error.Message); Assert.Null(error.ErrorCode); Assert.Equal("key3:\r\nTest Error 3", error.InnerError.Message); Assert.Equal(2, error.Details.Count); }
private Action <WriterTestConfiguration> WriteError(Func <XElement, XElement> fragmentExtractor, string expectedXml) { var sampleError = new ODataError(); return((testConfiguration) => { if (testConfiguration.IsRequest) { return; } TestWriterUtils.WriteAndVerifyTopLevelContent(new PayloadWriterTestDescriptor <ODataError>( this.Settings, sampleError, expectedXml, null, fragmentExtractor, null, /*disableXmlNamespaceNormalization*/ true), testConfiguration, (messageWriter) => messageWriter.WriteError(sampleError, false), this.Assert, baselineLogger: this.Logger); }); }
/// <summary> /// Reads a top-level error. /// </summary> /// <returns>An <see cref="ODataError"/> representing the read error.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.None - assumes that the Xml reader has not been used yet. /// Post-Condition: Any - the next node after the m:error end element or the empty m:error element node. /// </remarks> internal ODataError ReadTopLevelError() { DebugUtils.CheckNoExternalCallers(); Debug.Assert(this.ReadingResponse, "Top-level errors are only supported in responses."); Debug.Assert(this.XmlReader != null, "this.XmlReader != null"); Debug.Assert(!this.XmlReader.DisableInStreamErrorDetection, "!this.XmlReader.DetectInStreamErrors"); try { this.XmlReader.DisableInStreamErrorDetection = true; this.ReadPayloadStart(); this.AssertXmlCondition(XmlNodeType.Element); // check for the <m:error> element if (!this.XmlReader.NamespaceEquals(this.XmlReader.ODataMetadataNamespace) || !this.XmlReader.LocalNameEquals(this.XmlReader.ODataErrorElementName)) { throw new ODataErrorException( Strings.ODataAtomErrorDeserializer_InvalidRootElement(this.XmlReader.Name, this.XmlReader.NamespaceURI)); } ODataError error = ReadErrorElement(this.XmlReader, this.MessageReaderSettings.MessageQuotas.MaxNestingDepth); // The ReadErrorElement leaves the reader on the m:error end element or empty start element. // So read over that to consume the entire m:error element. this.XmlReader.Read(); this.ReadPayloadEnd(); return(error); } finally { this.XmlReader.DisableInStreamErrorDetection = false; } }
public void TestReadError() { MemoryStream ms = new MemoryStream(); using (var writer = AvroContainer.CreateWriter <Error>(ms, true, new AvroSerializerSettings(), Codec.Null)) using (var seqWriter = new SequentialWriter <Error>(writer, 24)) { seqWriter.Write(new Error { ErrorCode = "500", Message = "Internal Error" }); } ms.Seek(0, SeekOrigin.Begin); ODataError error = null; using (var omr = TestHelper.CreateMessageReader(ms, "avro/binary", AvroMediaTypeResolver.Instance, new EdmModel(), true)) { error = omr.ReadError(); } Assert.IsNotNull(error); Assert.AreEqual("500", error.ErrorCode); Assert.AreEqual("Internal Error", error.Message); }
/// <summary> /// Write an OData error. /// </summary> /// <param name='errorInstance'>The error information to write.</param> /// <param name="includeDebugInformation">If in debug mode error details will be included in the error.</param> public sealed override void WriteError(ODataError errorInstance, bool includeDebugInformation) { ExceptionUtils.CheckArgumentNotNull(errorInstance, "errorInstance"); this.VerifyNotDisposed(); this.CheckStartPayload(); try { this.EnterScope(WriterState.Error, this.scopes.Peek().Item); this.SerializeError(errorInstance, includeDebugInformation); } catch (Exception e) { if (!ExceptionUtils.IsCatchableExceptionType(e)) { throw; } // any exception is considered fatal; we transition into FatalExceptionThrown state and // do not allow any further writes. this.EnterScope(WriterState.FatalExceptionThrown, this.scopes.Peek().Item); throw; } }
/// <summary> /// Read a top-level error. /// </summary> /// <returns>A task which returns an <see cref="ODataError"/> representing the read error.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.None - The reader must not have been used yet. /// Post-Condition: JsonNodeType.EndOfInput /// </remarks> internal Task <ODataError> ReadTopLevelErrorAsync() { DebugUtils.CheckNoExternalCallers(); Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet."); Debug.Assert(!this.JsonReader.DisableInStreamErrorDetection, "!JsonReader.DisableInStreamErrorDetection"); this.JsonReader.AssertNotBuffering(); // prevent the buffering JSON reader from detecting in-stream errors - we read the error ourselves // to throw proper exceptions this.JsonReader.DisableInStreamErrorDetection = true; // We use this to store annotations and check for duplicate annotation names, but we don't really store properties in it. DuplicatePropertyNamesChecker duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker(); // Position the reader on the first node return(this.ReadPayloadStartAsync( ODataPayloadKind.Error, duplicatePropertyNamesChecker, /*isReadingNestedPayload*/ false, /*allowEmptyPayload*/ false) .FollowOnSuccessWith(t => { ODataError result = this.ReadTopLevelErrorImplementation(); Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: JsonNodeType.EndOfInput"); this.JsonReader.AssertNotBuffering(); return result; }) .FollowAlwaysWith(t => { this.JsonReader.DisableInStreamErrorDetection = false; })); }
/// <summary> /// Reads a property value which occurs in the "message" object scope. /// </summary> /// <param name="error">The <see cref="ODataError"/> object to update with the data from this property value.</param> /// <param name="propertyName">The name of the propety whose value is to be read.</param> /// <remarks> /// Pre-Condition: any - The value of the property being read. /// Post-Condition: JsonNodeType.Property - The property after the one being read. /// JsonNodeType.EndObject - The end of the "message" object. /// any - Anything else after the property value is an invalid payload (but won't fail in this method). /// </remarks> private void ReadPropertyValueInMessageObject(ODataError error, string propertyName) { switch (propertyName) { case JsonConstants.ODataErrorMessageLanguageName: error.MessageLanguage = this.JsonReader.ReadStringValue(JsonConstants.ODataErrorMessageLanguageName); break; case JsonConstants.ODataErrorMessageValueName: error.Message = this.JsonReader.ReadStringValue(JsonConstants.ODataErrorMessageValueName); break; default: if (ODataJsonLightReaderUtils.IsAnnotationProperty(propertyName)) { // ignore custom instance annotations this.JsonReader.SkipValue(); break; } // we only allow a 'lang' and 'value' properties in the value of the 'message' property throw new ODataException(Strings.ODataJsonErrorDeserializer_TopLevelErrorMessageValueWithInvalidProperty(propertyName)); } }
/// <summary> /// Writes an in-stream error. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> private void WriteInStreamErrorImplementation(ODataError error, bool includeDebugInformation) { if (this.outputInStreamErrorListener != null) { this.outputInStreamErrorListener.OnInStreamError(); } ODataAtomWriterUtils.WriteError(this.xmlWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth); }
/// <summary> /// Reads the JSON object which is the value of the "odata.error" property. /// </summary> /// <param name="error">The <see cref="ODataError"/> object to update with data from the payload.</param> /// <remarks> /// Pre-Condition: JsonNodeType.StartObject - The start of the "odata.error" object. /// any - Will throw if not StartObject. /// Post-Condition: any - The node after the "odata.error" object's EndNode. /// </remarks> private void ReadODataErrorObject(ODataError error) { this.ReadJsonObjectInErrorPayload((propertyName, duplicationPropertyNameChecker) => this.ReadPropertyValueInODataErrorObject(error, propertyName, duplicationPropertyNameChecker)); }
private void WriteError(ODataMessageWriterTestWrapper messageWriter, ODataError error, bool debug) { messageWriter.WriteError(error, debug); }
/// <summary> /// Reads the content of an error element. /// </summary> /// <param name="xmlReader">The Xml reader to read the error payload from.</param> /// <param name="maxInnerErrorDepth">The maximumum number of recursive internalexception elements to allow.</param> /// <returns>The <see cref="ODataError"/> representing the error.</returns> /// <remarks> /// This method is used to read top-level errors as well as in-stream errors (from inside the buffering Xml reader). /// Pre-Condition: XmlNodeType.Element - The m:error start element. /// Post-Condition: XmlNodeType.EndElement - The m:error end-element. /// XmlNodeType.Element - The empty m:error start element. /// </remarks> internal static ODataError ReadErrorElement(BufferingXmlReader xmlReader, int maxInnerErrorDepth) { Debug.Assert(xmlReader != null, "this.XmlReader != null"); Debug.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader.NodeType == XmlNodeType.Element"); Debug.Assert(xmlReader.LocalName == AtomConstants.ODataErrorElementName, "Expected reader to be positioned on <m:error> element."); Debug.Assert(xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace), "this.XmlReader.NamespaceEquals(atomizedMetadataNamespace)"); ODataError error = new ODataError(); DuplicateErrorElementPropertyBitMask elementsReadBitmask = DuplicateErrorElementPropertyBitMask.None; if (!xmlReader.IsEmptyElement) { // Move to the first child node of the element. xmlReader.Read(); do { switch (xmlReader.NodeType) { case XmlNodeType.EndElement: // end of the <m:error> element continue; case XmlNodeType.Element: if (xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace)) { switch (xmlReader.LocalName) { // <m:code> case AtomConstants.ODataErrorCodeElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.Code, AtomConstants.ODataErrorCodeElementName); error.ErrorCode = xmlReader.ReadElementValue(); continue; // <m:message > case AtomConstants.ODataErrorMessageElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.Message, AtomConstants.ODataErrorMessageElementName); error.Message = xmlReader.ReadElementValue(); continue; // <m:innererror> case AtomConstants.ODataInnerErrorElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.InnerError, AtomConstants.ODataInnerErrorElementName); error.InnerError = ReadInnerErrorElement(xmlReader, 0 /* recursionDepth */, maxInnerErrorDepth); continue; default: break; } } break; default: break; } xmlReader.Skip(); } while (xmlReader.NodeType != XmlNodeType.EndElement); } return error; }
/// <summary> /// Reads a property value which occurs in the "error" object scope. /// </summary> /// <param name="error">The <see cref="ODataError"/> object to update with the data from this property value.</param> /// <param name="propertyName">The name of the property whose value is to be read.</param> /// <param name="duplicationPropertyNameChecker">DuplicatePropertyNamesChecker to use for extracting property annotations /// targetting any custom instance annotations on the error.</param> /// <remarks> /// Pre-Condition: any - The value of the property being read. /// Post-Condition: JsonNodeType.Property - The property after the one being read. /// JsonNodeType.EndObject - The end of the "error" object. /// any - Anything else after the property value is an invalid payload (but won't fail in this method). /// </remarks> private void ReadPropertyValueInODataErrorObject(ODataError error, string propertyName, DuplicatePropertyNamesChecker duplicationPropertyNameChecker) { switch (propertyName) { case JsonConstants.ODataErrorCodeName: error.ErrorCode = this.JsonReader.ReadStringValue(JsonConstants.ODataErrorCodeName); break; case JsonConstants.ODataErrorMessageName: error.Message = this.JsonReader.ReadStringValue(JsonConstants.ODataErrorMessageName); break; case JsonConstants.ODataErrorTargetName: error.Target = this.JsonReader.ReadStringValue(JsonConstants.ODataErrorTargetName); break; case JsonConstants.ODataErrorDetailsName: error.Details = this.ReadDetails(); break; case JsonConstants.ODataErrorInnerErrorName: error.InnerError = this.ReadInnerError(0 /* recursionDepth */); break; default: // See if it's an instance annotation if (ODataJsonLightReaderUtils.IsAnnotationProperty(propertyName)) { ODataJsonLightPropertyAndValueDeserializer valueDeserializer = new ODataJsonLightPropertyAndValueDeserializer(this.JsonLightInputContext); object typeName = null; var odataAnnotations = duplicationPropertyNameChecker.GetODataPropertyAnnotations(propertyName); if (odataAnnotations != null) { odataAnnotations.TryGetValue(ODataAnnotationNames.ODataType, out typeName); } var value = valueDeserializer.ReadNonEntityValue( typeName as string, null /*expectedValueTypeReference*/, null /*duplicatePropertiesNamesChecker*/, null /*collectionValidator*/, false /*validateNullValue*/, false /*isTopLevelPropertyValue*/, false /*insideComplexValue*/, propertyName); error.GetInstanceAnnotations().Add(new ODataInstanceAnnotation(propertyName, value.ToODataValue())); } else { // we only allow a 'code', 'message', 'target', 'details, and 'innererror' properties // in the value of the 'error' property or custom instance annotations throw new ODataException(Strings.ODataJsonLightErrorDeserializer_TopLevelErrorValueWithInvalidProperty(propertyName)); } break; } }
/// <summary> /// Read a top-level error. /// </summary> /// <returns>An <see cref="ODataError"/> representing the read error.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.Property - The first property of the top level object. /// JsonNodeType.EndObject - If there are no properties in the top level object. /// any - Will throw if anything else. /// Post-Condition: JsonNodeType.EndOfInput /// </remarks> private ODataError ReadTopLevelErrorImplementation() { ODataError error = null; while (this.JsonReader.NodeType == JsonNodeType.Property) { string propertyName = this.JsonReader.ReadPropertyName(); if (string.CompareOrdinal(JsonLightConstants.ODataErrorPropertyName, propertyName) != 0) { // we only allow a single 'error' property for a top-level error object throw new ODataException(Strings.ODataJsonErrorDeserializer_TopLevelErrorWithInvalidProperty(propertyName)); } if (error != null) { throw new ODataException(OData.Core.Strings.ODataJsonReaderUtils_MultipleErrorPropertiesWithSameName(JsonLightConstants.ODataErrorPropertyName)); } error = new ODataError(); this.ReadODataErrorObject(error); } // Read the end of the error object this.JsonReader.ReadEndObject(); // Read the end of the response. this.ReadPayloadEnd(false /*isReadingNestedPayload*/); Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: JsonNodeType.EndOfInput"); return error; }
public new TestBadRequestResult BadRequest(ODataError error) { return(new TestBadRequestResult(base.BadRequest(error))); }
public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, ODataError oDataError) { if (request.ShouldIncludeErrorDetail()) { return(request.CreateResponse(statusCode, oDataError)); } else { return(request.CreateResponse( statusCode, new ODataError { ErrorCode = oDataError.ErrorCode, Message = oDataError.Message, })); } }
/// <summary> /// Visits an error. /// </summary> /// <param name="error">The error to visit.</param> protected abstract T VisitError(ODataError error);
public ODataErrorTests() { this.odataError = new ODataError(); }
/// <summary> /// Writes an ODataError with the given custom instance annotation to the test stream. /// </summary> private void WriteError(params KeyValuePair<string, ODataValue>[] annotations) { var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true }; writerSettings.SetContentType(ODataFormat.Json); writerSettings.SetServiceDocumentUri(new Uri("http://example.com/")); IODataResponseMessage messageToWrite = new InMemoryMessage { StatusCode = 400, Stream = this.stream }; var error = new ODataError(); var instanceAnnotations = new Collection<ODataInstanceAnnotation>(); error.SetInstanceAnnotations(instanceAnnotations); foreach (var pair in annotations) { ODataInstanceAnnotation annotation = new ODataInstanceAnnotation(pair.Key, pair.Value); instanceAnnotations.Add(annotation); } using (var writer = new ODataMessageWriter(messageToWrite, writerSettings, this.model)) { writer.WriteError(error, false); } }
private static ODataValue RunBasicVerificationAndGetAnnotationValue(string name, ODataError error) { error.Should().NotBeNull(); var instanceAnnotations = error.InstanceAnnotations; instanceAnnotations.Should().NotBeNull("there was an instance annotation in the payload."); instanceAnnotations.Should().NotBeEmpty("there was an instance annotation in the payload."); var annotation = instanceAnnotations.Where(instanceAnnotation => instanceAnnotation.Name.Equals(name)).FirstOrDefault(); annotation.Should().NotBeNull("an instance annotation with the requested name was in the payload."); return annotation.Value; }
/// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> private void WriteErrorImplementation(ODataError error, bool includeDebugInformation) { ODataAtomSerializer atomSerializer = new ODataAtomSerializer(this); atomSerializer.WriteTopLevelError(error, includeDebugInformation); }
/// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <returns>A func which performs the actual writing given the stream to write to.</returns> private Func<Stream, AsyncWriter> WriteErrorImplementation(ODataError error, bool includeDebugInformation) { this.VerifyWriterNotUsed(); ExceptionUtils.CheckArgumentNotNull(error, "error"); if (!this.writingResponse) { // top-level errors can only be written for response messages throw new ODataException(Strings.ODataMessageWriter_ErrorPayloadInRequest); } // Set the content type header here since all headers have to be set before getting the stream this.SetOrVerifyHeaders(ODataPayloadKind.Error); return (stream) => this.WriteError(stream, error, includeDebugInformation); }
/// <summary> /// Write a top-level error to the given stream. This method creates an /// async buffered stream, writes the error to it and returns an <see cref="AsyncWriter"/> /// that can be used to flush and close/dispose the stream. /// </summary> /// <param name="stream">The stream to write the links to.</param> /// <param name="error">The error to write as message payload.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> /// <returns>An <see cref="AsyncWriter"/> that can be used to flush and close/dispose the stream.</returns> private AsyncWriter WriteError(Stream stream, ODataError error, bool includeDebugInformation) { Debug.Assert(this.writerPayloadKind != ODataPayloadKind.Unsupported, "Expected payload kind, format and encoding to be set by now."); return this.WriteTopLevelContent( stream, (xmlWriter) => ODataAtomWriterUtils.WriteError(xmlWriter, error, includeDebugInformation), (jsonWriter) => ODataJsonWriterUtils.WriteTopLevelError(jsonWriter, error, includeDebugInformation, this.writingResponse), Strings.ODataMessageWriter_InvalidContentTypeForWritingError, InternalErrorCodes.ODataMessageWriter_WriteError); }
public new TestConflictResult Conflict(ODataError error) { return(new TestConflictResult(base.Conflict(error))); }
/// <summary> /// Reads the JSON object which is the value of the "error" property. /// </summary> /// <param name="error">The <see cref="ODataError"/> object to update with data from the payload.</param> /// <remarks> /// Pre-Condition: JsonNodeType.StartObject - The start of the "error" object. /// any - Will throw if not StartObject. /// Post-Condition: any - The node after the "error" object's EndNode. /// </remarks> private void ReadODataErrorObject(ODataError error) { this.ReadJsonObjectInErrorPayload((propertyName, duplicationPropertyNameChecker) => this.ReadPropertyValueInODataErrorObject(error, propertyName, duplicationPropertyNameChecker)); }
public void WriteTopLevelErrorHasCorrectDefaults() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError(); serializer.WriteTopLevelError(error, false); }); result.Should().Contain("\"code\":\"\""); result.Should().Contain("\"message\":\"\""); result.Should().NotContain("\"target\""); result.Should().NotContain("\"details\""); }
/// <summary> /// Writes a top-level error payload. /// </summary> /// <param name="error">The error instance to write.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> internal void WriteTopLevelError(ODataError error, bool includeDebugInformation) { Debug.Assert(this.MessageWriterSettings != null, "this.MessageWriterSettings != null"); this.WritePayloadStart(); ODataAtomWriterUtils.WriteError(this.XmlWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth); this.WritePayloadEnd(); }
public void WriteTopLevelErrorWithCollectionOfComplexInstanceAnnotationWithNoTypeNameShouldThrow() { SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError(); var instanceAnnotations = new Collection<ODataInstanceAnnotation>(); var collection = new ODataCollectionValue { Items = new[] { new ODataComplexValue(), new ODataComplexValue { TypeName = "ns.ErrorDetails" } } }; ODataInstanceAnnotation annotation = new ODataInstanceAnnotation("sample.collection", collection); instanceAnnotations.Add(annotation); error.InstanceAnnotations = instanceAnnotations; Action writeError = () => serializer.WriteTopLevelError(error, false); writeError.ShouldThrow<ODataException>().WithMessage(Strings.WriterValidationUtils_MissingTypeNameWithMetadata); }); }
/// <summary> /// Reads the content of an error element. /// </summary> /// <param name="xmlReader">The Xml reader to read the error payload from.</param> /// <param name="maxInnerErrorDepth">The maximumum number of recursive internalexception elements to allow.</param> /// <returns>The <see cref="ODataError"/> representing the error.</returns> /// <remarks> /// This method is used to read top-level errors as well as in-stream errors (from inside the buffering Xml reader). /// Pre-Condition: XmlNodeType.Element - The m:error start element. /// Post-Condition: XmlNodeType.EndElement - The m:error end-element. /// XmlNodeType.Element - The empty m:error start element. /// </remarks> internal static ODataError ReadErrorElement(BufferingXmlReader xmlReader, int maxInnerErrorDepth) { Debug.Assert(xmlReader != null, "this.XmlReader != null"); Debug.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader.NodeType == XmlNodeType.Element"); Debug.Assert(xmlReader.LocalName == AtomConstants.ODataErrorElementName, "Expected reader to be positioned on <m:error> element."); Debug.Assert(xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace), "this.XmlReader.NamespaceEquals(atomizedMetadataNamespace)"); ODataError error = new ODataError(); DuplicateErrorElementPropertyBitMask elementsReadBitmask = DuplicateErrorElementPropertyBitMask.None; if (!xmlReader.IsEmptyElement) { // Move to the first child node of the element. xmlReader.Read(); do { switch (xmlReader.NodeType) { case XmlNodeType.EndElement: // end of the <m:error> element continue; case XmlNodeType.Element: if (xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace)) { switch (xmlReader.LocalName) { // <m:code> case AtomConstants.ODataErrorCodeElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.Code, AtomConstants.ODataErrorCodeElementName); error.ErrorCode = xmlReader.ReadElementValue(); continue; // <m:message > case AtomConstants.ODataErrorMessageElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.Message, AtomConstants.ODataErrorMessageElementName); error.Message = xmlReader.ReadElementValue(); continue; // <m:innererror> case AtomConstants.ODataInnerErrorElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.InnerError, AtomConstants.ODataInnerErrorElementName); error.InnerError = ReadInnerErrorElement(xmlReader, 0 /* recursionDepth */, maxInnerErrorDepth); continue; default: break; } } break; default: break; } xmlReader.Skip(); }while (xmlReader.NodeType != XmlNodeType.EndElement); } return(error); }
/// <summary> /// Write an error message. /// </summary> /// <param name="writer">The Xml writer to write to.</param> /// <param name="error">The error instance to write.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> internal static void WriteError(XmlWriter writer, ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(writer != null, "writer != null"); Debug.Assert(error != null, "error != null"); string code, message, messageLanguage; ODataUtilsInternal.GetErrorDetails(error, out code, out message, out messageLanguage); string innerError = includeDebugInformation ? error.InnerError : null; WriteError(writer, code, message, messageLanguage, innerError); }
public void WriteTopLevelErrorWithCollectionOfComplexInstanceAnnotation() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError(); var instanceAnnotations = new Collection<ODataInstanceAnnotation>(); var collection = new ODataCollectionValue { TypeName = "Collection(ns.ErrorDetails)", Items = new[] { new ODataComplexValue(), new ODataComplexValue { TypeName = "ns.ErrorDetails" } } }; ODataInstanceAnnotation annotation = new ODataInstanceAnnotation("sample.collection", collection); instanceAnnotations.Add(annotation); error.InstanceAnnotations = instanceAnnotations; serializer.WriteTopLevelError(error, false); }); result.Should().Contain("\"[email protected]\":\"#Collection(ns.ErrorDetails)\",\"@sample.collection\":[{},{}]"); }
/// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> public void WriteError(ODataError error, bool includeDebugInformation) { this.WriteToStream(this.WriteErrorImplementation(error, includeDebugInformation)); }
/// <summary> /// Reads the JSON object which is the value of the "message" property. /// </summary> /// <param name="error">The <see cref="ODataError"/> object to update with data from the payload.</param> /// <remarks> /// Pre-Condition: JsonNodeType.StartObject - The start of the "message" object. /// any - Will throw if not StartObject. /// Post-Condition: any - The node after the "message" object's EndNode. /// </remarks> private void ReadErrorMessageObject(ODataError error) { this.ReadJsonObjectInErrorPayload((propertyName, duplicatePropertyNamesChecker) => this.ReadPropertyValueInMessageObject(error, propertyName)); }
/// <summary> /// Asynchronously writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <returns>A task representing the asynchronous operation of writing the error.</returns> public Task WriteErrorAsync(ODataError error, bool includeDebugInformation) { return this.WriteToStreamAsync(this.WriteErrorImplementation(error, includeDebugInformation)); }
internal void WriteTopLevelError(ODataError error, bool includeDebugInformation) { this.WriteTopLevelPayload(() => ODataJsonWriterUtils.WriteError(this.JsonWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth), true); }
/// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteError(ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WriteErrorImplementation(error, includeDebugInformation); this.Flush(); }
public async Task WriteErrorAsync_InnerErrorWithNestedNullValue() { IDictionary <string, ODataValue> properties = new Dictionary <string, ODataValue>(); properties.Add("stacktrace", "NormalString".ToODataValue()); properties.Add("MyNewObject", new ODataResourceValue() { TypeName = "ComplexValue", Properties = new List <ODataProperty>() { new ODataProperty { Name = "NestedResourcePropertyName", Value = new ODataResourceValue() { Properties = new List <ODataProperty>() { new ODataProperty { Name = "InnerMostPropertyName", Value = "InnerMostPropertyValue" } } } } } }); IDictionary <string, ODataValue> nestedDict = new Dictionary <string, ODataValue>(); nestedDict.Add("nested", null); var error = new ODataError { Target = "any target", Details = new[] { new ODataErrorDetail { ErrorCode = "500", Target = "any target", Message = "any msg" } }, InnerError = new ODataInnerError(properties) { InnerError = new ODataInnerError(nestedDict) } }; await ODataJsonWriterUtils.WriteErrorAsync( this.jsonWriter, this.writeInstanceAnnotationsDelegate, error, includeDebugInformation : true, maxInnerErrorDepth : 5); var result = stringWriter.GetStringBuilder().ToString(); Assert.Equal("{\"error\":{" + "\"code\":\"\"," + "\"message\":\"\"," + "\"target\":\"any target\"," + "\"details\":[{\"code\":\"500\",\"target\":\"any target\",\"message\":\"any msg\"}]," + "\"innererror\":{" + "\"stacktrace\":\"NormalString\"," + "\"MyNewObject\":{" + "\"NestedResourcePropertyName\":{\"InnerMostPropertyName\":\"InnerMostPropertyValue\"}" + "}," + "\"internalexception\":{\"nested\":null}" + "}" + "}}", result); }
/// <summary> /// Write an error message. /// </summary> /// <param name="writer">The Xml writer to write to.</param> /// <param name="error">The error instance to write.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> /// <param name="maxInnerErrorDepth">The maximumum number of nested inner errors to allow.</param> internal static void WriteError(XmlWriter writer, ODataError error, bool includeDebugInformation, int maxInnerErrorDepth) { ErrorUtils.WriteXmlError(writer, error, includeDebugInformation, maxInnerErrorDepth); }
/// <summary> /// Visits an item in the object model. /// </summary> /// <param name="objectModelItem">The item to visit.</param> public virtual T Visit(object objectModelItem) { ODataResourceSet feed = objectModelItem as ODataResourceSet; if (feed != null) { return(this.VisitFeed(feed)); } ODataResource entry = objectModelItem as ODataResource; if (entry != null) { return(this.VisitEntry(entry)); } ODataProperty property = objectModelItem as ODataProperty; if (property != null) { return(this.VisitProperty(property)); } ODataNestedResourceInfo navigationLink = objectModelItem as ODataNestedResourceInfo; if (navigationLink != null) { return(this.VisitNavigationLink(navigationLink)); } ODataResourceValue resourceValue = objectModelItem as ODataResourceValue; if (resourceValue != null) { return(this.VisitResourceValue(resourceValue)); } ODataCollectionValue collection = objectModelItem as ODataCollectionValue; if (collection != null) { return(this.VisitCollectionValue(collection)); } ODataStreamReferenceValue streamReferenceValue = objectModelItem as ODataStreamReferenceValue; if (streamReferenceValue != null) { return(this.VisitStreamReferenceValue(streamReferenceValue)); } ODataCollectionStart collectionStart = objectModelItem as ODataCollectionStart; if (collectionStart != null) { return(this.VisitCollectionStart(collectionStart)); } ODataServiceDocument serviceDocument = objectModelItem as ODataServiceDocument; if (serviceDocument != null) { return(this.VisitWorkspace(serviceDocument)); } ODataEntitySetInfo entitySetInfo = objectModelItem as ODataEntitySetInfo; if (entitySetInfo != null) { return(this.VisitResourceCollection(entitySetInfo)); } ODataError error = objectModelItem as ODataError; if (error != null) { return(this.VisitError(error)); } ODataInnerError innerError = objectModelItem as ODataInnerError; if (innerError != null) { return(this.VisitInnerError(innerError)); } ODataEntityReferenceLinks entityReferenceLinks = objectModelItem as ODataEntityReferenceLinks; if (entityReferenceLinks != null) { return(this.VisitEntityReferenceLinks(entityReferenceLinks)); } ODataEntityReferenceLink entityReferenceLink = objectModelItem as ODataEntityReferenceLink; if (entityReferenceLink != null) { return(this.VisitEntityReferenceLink(entityReferenceLink)); } ODataAction action = objectModelItem as ODataAction; if (action != null) { return(this.VisitODataOperation(action)); } ODataFunction function = objectModelItem as ODataFunction; if (function != null) { return(this.VisitODataOperation(function)); } ODataParameters parameters = objectModelItem as ODataParameters; if (parameters != null) { return(this.VisitParameters(parameters)); } ODataBatch batch = objectModelItem as ODataBatch; if (batch != null) { return(this.VisitBatch(batch)); } if (objectModelItem == null || objectModelItem is ODataPrimitiveValue || objectModelItem.GetType().IsValueType || objectModelItem is string || objectModelItem is byte[] || objectModelItem is ISpatial) { return(this.VisitPrimitiveValue(objectModelItem)); } if (objectModelItem is ODataUntypedValue) { object val = ODataObjectModelVisitor.ParseJsonToPrimitiveValue( (objectModelItem as ODataUntypedValue).RawValue); return(this.VisitPrimitiveValue(val)); } return(this.VisitUnsupportedValue(objectModelItem)); }
/// <summary> /// Writes an <see cref="ODataError"/> into the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <remarks> /// This method is called if the ODataMessageWriter.WriteError is called once some other /// write operation has already started. /// The method should write the in-stream error representation for the specific format into the current payload. /// Before the method is called no flush is performed on the output context or any active writer. /// It is the responsibility of this method to flush the output before the method returns. /// </remarks> internal override void WriteInStreamError(ODataError error, bool includeDebugInformation) { this.AssertSynchronous(); this.WriteInStreamErrorImplementation(error, includeDebugInformation); this.Flush(); }
public new TestNotFoundResult NotFound(ODataError error) { return(new TestNotFoundResult(base.NotFound(error))); }
/// <summary> /// Writes an <see cref="ODataError"/> into the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <returns>Task which represents the pending write operation.</returns> /// <remarks> /// This method is called if the ODataMessageWriter.WriteError is called once some other /// write operation has already started. /// The method should write the in-stream error representation for the specific format into the current payload. /// Before the method is called no flush is performed on the output context or any active writer. /// It is the responsibility of this method to make sure that all the data up to this point are written before /// the in-stream error is written. /// It is the responsibility of this method to flush the output before the task finishes. /// </remarks> internal override Task WriteInStreamErrorAsync(ODataError error, bool includeDebugInformation) { this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WriteInStreamErrorImplementation(error, includeDebugInformation); return this.FlushAsync(); }); }
public new TestUnauthorizedResult Unauthorized(ODataError error) { return(new TestUnauthorizedResult(base.Unauthorized(error))); }
/// <summary> /// Writes an in-stream error. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> private void WriteInStreamErrorImplementation(ODataError error, bool includeDebugInformation) { if (this.outputInStreamErrorListener != null) { this.outputInStreamErrorListener.OnInStreamError(); } JsonLightInstanceAnnotationWriter instanceAnnotationWriter = new JsonLightInstanceAnnotationWriter(new ODataJsonLightValueSerializer(this), this.TypeNameOracle); ODataJsonWriterUtils.WriteError(this.JsonWriter, instanceAnnotationWriter.WriteInstanceAnnotationsForError, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth, /*writingJsonLight*/ true); }
public new TestUnprocessableEntityResult UnprocessableEntity(ODataError error) { return(new TestUnprocessableEntityResult(base.UnprocessableEntity(error))); }
/// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> private void WriteErrorImplementation(ODataError error, bool includeDebugInformation) { ODataJsonLightSerializer jsonLightSerializer = new ODataJsonLightSerializer(this, false); jsonLightSerializer.WriteTopLevelError(error, includeDebugInformation); }