Esempio n. 1
0
 public void DefaultValuesTest()
 {
     ODataError error = new ODataError();
     this.Assert.IsNull(error.ErrorCode, "Expected null default value for property 'ErrorCode'.");
     this.Assert.IsNull(error.Message, "Expected null default value for property 'Message'.");
     this.Assert.IsNull(error.InnerError, "Expected null default value for property 'InnerError'.");
 }
 public override void WriteError(ODataError error, bool includeDebugInformation)
 {
     var schema = this.AvroWriter.UpdateSchema(error, null);
     var obj = ODataAvroConvert.FromODataObject(error, schema);
     this.AvroWriter.Write(obj);
     this.Flush();
 }
Esempio n. 3
0
        public void PropertySettersNullTest()
        {
            ODataError error = new ODataError()
            {
                ErrorCode = "500",
                Message = "Fehler! Bitte kontaktieren Sie den Administrator!",
                Target = "any target",
                Details =
                    new List<ODataErrorDetail>
                    {
                        new ODataErrorDetail { ErrorCode = "401", Message = "any msg", Target = "another target" }
                    },
                InnerError = new ODataInnerError { Message = "No inner error" },
            };

            error.ErrorCode = null;
            error.Message = null;
            error.Target = null;
            error.Details = null;
            error.InnerError = null;

            this.Assert.IsNull(error.ErrorCode, "Expected null default value for property 'ErrorCode'.");
            this.Assert.IsNull(error.Message, "Expected null default value for property 'Message'.");
            this.Assert.IsNull(error.Target, "Expected null default value for property 'Target'.");
            this.Assert.IsNull(error.Details, "Expected null default value for property 'Details'.");
            this.Assert.IsNull(error.InnerError, "Expected null default value for property 'InnerError'.");
        }
Esempio n. 4
0
        /// <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>
        internal static void GetErrorDetails(ODataError error, out string code, out string message)
        {
            Debug.Assert(error != null, "error != null");

            code = error.ErrorCode ?? string.Empty;
            message = error.Message ?? string.Empty;
        }
Esempio n. 5
0
        public void PropertyGettersAndSettersTest()
        {
            string errorCode = "500";
            string message = "Fehler! Bitte kontaktieren Sie den Administrator!";
            var target = "any target";
            var details = new List<ODataErrorDetail>
            {
                new ODataErrorDetail { ErrorCode = "401", Message = "any msg", Target = "another target" }
            };
            ODataInnerError innerError = new ODataInnerError { Message = "No inner error" };

            ODataError error = new ODataError()
            {
                ErrorCode = errorCode,
                Message = message,
                Target = target,
                Details = details,
                InnerError = innerError
            };

            this.Assert.AreEqual(errorCode, error.ErrorCode, "Expected equal error code values.");
            this.Assert.AreEqual(message, error.Message, "Expected equal message values.");
            this.Assert.AreEqual(target, error.Target, "Expected equal target values.");
            this.Assert.AreSame(details, error.Details, "Expected equal error detail values.");
            this.Assert.AreSame(innerError, error.InnerError, "Expected equal inner error values.");
        }
        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 WriteTopLevelErrorUsesProvidedErrorCode()
        {
            var result = SetupSerializerAndRunTest(null, serializer =>
            {
                ODataError error = new ODataError { ErrorCode = "Error Code" };
                serializer.WriteTopLevelError(error, false);
            });

            result.Should().Contain("\"code\":\"Error Code\"");
        }
        private void BuildODataError(out ODataError error, out HttpStatusCode statusCode)
        {
            // Default to 500 (InternalServerError), it will be overried below if necessary.
            statusCode = HttpStatusCode.InternalServerError;

            ODataServiceException ose = this.HandledException as ODataServiceException;

            if (ose != null)
            {
                statusCode = ose.StatusCode;
            }

            ODataContentTypeException octe = this.HandledException as ODataContentTypeException;

            if (octe != null)
            {
                statusCode = HttpStatusCode.UnsupportedMediaType;
            }


            ODataUnrecognizedPathException oupe = this.HandledException as ODataUnrecognizedPathException;

            if (oupe != null)
            {
                statusCode = HttpStatusCode.NotFound;
            }

            ODataErrorException oee = this.HandledException as ODataErrorException;

            if (oee != null)
            {
                error = this.BuildODataError(statusCode, this.HandledException);

                if (!string.IsNullOrEmpty(oee.Error.ErrorCode))
                {
                    error.ErrorCode = oee.Error.ErrorCode;
                }

                if (!string.IsNullOrEmpty(oee.Error.Message))
                {
                    error.Message = oee.Error.Message;
                }

                if (oee.Error.InnerError != null)
                {
                    error.InnerError = oee.Error.InnerError;
                }
            }
            else
            {
                // All the other exception will go here.
                error = this.BuildODataError(statusCode, this.HandledException);
            }
        }
Esempio n. 9
0
        /// <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 WriteXmlError(XmlWriter writer, ODataError error, bool includeDebugInformation, int maxInnerErrorDepth)
        {
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(error != null, "error != null");

            string code, message;
            ErrorUtils.GetErrorDetails(error, out code, out message);

            ODataInnerError innerError = includeDebugInformation ? error.InnerError : null;
            WriteXmlError(writer, code, message, innerError, maxInnerErrorDepth);
        }
        /// <summary>
        /// Compares two <see cref="ODataError"/> instances and returns true if they are equal. Otherwise returns false.
        /// </summary>
        /// <param name="first">The first <see cref="ODataError"/> to use in the comparison.</param>
        /// <param name="second">The second <see cref="ODataError"/> to use in the comparison.</param>
        /// <returns>true if the <paramref name="first"/> and <paramref name="second"/> error instances are equal; otherwise false.</returns>
        public static bool AreEqual(ODataError first, ODataError second)
        {
            if (first == null && second == null) return true;
            if (first == null || second == null) return false;

            if (string.CompareOrdinal(first.ErrorCode, second.ErrorCode) != 0) return false;
            if (string.CompareOrdinal(first.Message, second.Message) != 0) return false;
            if (!AreEqual(first.InnerError, second.InnerError)) return false;

            return true;
        }
        /// <summary>
        /// Creates an ExpectedException for ODataErrorException typed exceptions.
        /// </summary>
        /// <param name="expectedODataError">The expected value of the exception's Error property.</param>
        /// <returns>An ExpectedException for this expected ODataException.</returns>
        public static ExpectedException ODataErrorException(ODataError expectedODataError)
        {
            var expectedException = new ExpectedException(typeof(ODataErrorException));
            expectedException.CustomVerification =
                (e) =>
                {
                    if (!ODataObjectModelValidationUtils.AreEqual(expectedODataError, ((ODataErrorException)e).Error))
                    {
                        throw new DataComparisonException("Expected ODataError instances to be equal.");
                    }
                };

            return expectedException;
        }
        /// <summary>
        /// Creates an ExpectedException for ODataErrorException typed exceptions.
        /// </summary>
        /// <param name="expectedODataError">The expected value of the exception's Error property.</param>
        /// <param name="resourceKey">The resource key to look up the expected message.</param>
        /// <param name="messageArguments">Arguments for the expected exception message.</param>
        /// <returns>An ExpectedException for this expected ODataException.</returns>
        public static ExpectedException ODataErrorException(ODataError expectedODataError, string resourceKey, params string[] messageArguments)
        {
            var expectedException = new ExpectedException(typeof(ODataErrorException), GetResourceVerifier(DataFxAssemblyRef.OData).CreateExpectedError(resourceKey, messageArguments));
            expectedException.CustomVerification = 
                (e) =>
                {
                    if (!ODataObjectModelValidationUtils.AreEqual(expectedODataError, ((ODataErrorException)e).Error))
                    {
                        throw new DataComparisonException("Expected ODataError instances to be equal.");
                    }
                };

            return expectedException;
        }
        public void ODataErrorSerializer_Works()
        {
            // Arrange
            ODataErrorSerializer serializer = new ODataErrorSerializer();
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);
            ODataError error = new ODataError { Message = "Error!!!" };

            // Act
            serializer.WriteObject(error, typeof(ODataError), new ODataMessageWriter(message), new ODataSerializerContext());

            // Assert
            stream.Seek(0, SeekOrigin.Begin);
            XElement element = XElement.Load(stream);
            Assert.Equal("Error!!!", element.Descendants().Single(e => e.Name.LocalName == "message").Value);
        }
Esempio n. 14
0
        public void PropertySettersNullTest()
        {
            ODataError error = new ODataError()
                {
                    ErrorCode = "500",
                    Message = "Fehler! Bitte kontaktieren Sie den Administrator!",
                    InnerError = new ODataInnerError { Message = "No inner error" },
                };

            error.ErrorCode = null;
            error.Message = null;
            error.InnerError = null;

            this.Assert.IsNull(error.ErrorCode, "Expected null default value for property 'ErrorCode'.");
            this.Assert.IsNull(error.Message, "Expected null default value for property 'Message'.");
            this.Assert.IsNull(error.InnerError, "Expected null default value for property 'InnerError'.");
        }
Esempio n. 15
0
        public void PropertyGettersAndSettersTest()
        {
            string errorCode = "500";
            string message = "Fehler! Bitte kontaktieren Sie den Administrator!";
            ODataInnerError innerError = new ODataInnerError { Message = "No inner error" };

            ODataError error = new ODataError()
            {
                ErrorCode = errorCode,
                Message = message,
                InnerError = innerError
            };

            this.Assert.AreEqual(errorCode, error.ErrorCode, "Expected equal error code values.");
            this.Assert.AreEqual(message, error.Message, "Expected equal message values.");
            this.Assert.AreSame(innerError, error.InnerError, "Expected equal inner error values.");
        }
        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);
        }
Esempio n. 17
0
 /// <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 virtual Task WriteInStreamErrorAsync(ODataError error, bool includeDebugInformation)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
 }
Esempio n. 18
0
 /// <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>
 public virtual void WriteError(ODataError error, bool includeDebugInformation)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
 }
Esempio n. 19
0
        public void UseWriterOnceTests()
        {
            Uri baseUri = new Uri("http://www.odata.org/");

            ODataError error = new ODataError();
            ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = new Uri("http://www.odata.org") };
            ODataEntityReferenceLinks links = new ODataEntityReferenceLinks
            {
                Links = new ODataEntityReferenceLink[] { link, link, link },
            };

            ODataServiceDocument serviceDocument = ObjectModelUtils.CreateDefaultWorkspace();
            ODataProperty property = new ODataProperty() { Name = "FirstName", Value = "Bill" };
            object rawValue = 42;

            // TODO: add WriteMetadataDocumentAsync() here once implemented.
            UseWriterOnceTestCase[] messageWriterOperations = new UseWriterOnceTestCase[]
            {
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.CreateODataCollectionWriter() },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.CreateODataEntryWriter() },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.CreateODataEntryWriter() },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteError(error, false), IsWriteError = true },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteEntityReferenceLink(link) },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteEntityReferenceLinks(links) },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteProperty(property) },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteServiceDocument(serviceDocument) },
                new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteValue(rawValue), IsWriteValue = true },
            };

            var testCases = messageWriterOperations.Combinations(2);

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testCase, testConfiguration) =>
                {
                    ODataMessageWriterSettings settingsWithBaseUri = testConfiguration.MessageWriterSettings.Clone();
                    settingsWithBaseUri.PayloadBaseUri = baseUri;
                    settingsWithBaseUri.SetServiceDocumentUri(ServiceDocumentUri);

                    using (var memoryStream = new TestStream())
                    {
                        TestMessage testMessage;
                        using (ODataMessageWriterTestWrapper messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert, out testMessage, settingsWithBaseUri))
                        {
                            testCase[0].WriterMethod(messageWriter);

                            string expectedException = "The ODataMessageWriter has already been used to write a message payload. An ODataMessageWriter can only be used once to write a payload for a given message.";
                            if (testCase[0].IsWriteValue && testCase[1].IsWriteError)
                            {
                                expectedException = "The WriteError method or the WriteErrorAsync method on ODataMessageWriter cannot be called after the WriteValue method or the WriteValueAsync method is called. In OData, writing an in-stream error for raw values is not supported.";
                            }
                            else if (!testCase[0].IsWriteError && testCase[1].IsWriteError)
                            {
                                expectedException = null;
                            }

                            TestExceptionUtils.ExpectedException<ODataException>(this.Assert, () => testCase[1].WriterMethod(messageWriter), expectedException);
                        }
                    }
                });
        }
Esempio n. 20
0
 /// <summary>Creates a new instance of the <see cref="T:Microsoft.OData.Core.ODataErrorException" /> class with an error message and an <see cref="T:Microsoft.OData.Core.ODataError" /> object.</summary>
 /// <param name="message">The plain text error message for this exception.</param>
 /// <param name="error">The <see cref="T:Microsoft.OData.Core.ODataError" /> instance representing the error read from the payload.</param>
 public ODataErrorException(string message, ODataError error)
     : this(message, null, error)
 {
 }
Esempio n. 21
0
 /// <summary>Creates a new instance of the <see cref="T:Microsoft.OData.Core.ODataErrorException" /> class with an <see cref="T:Microsoft.OData.Core.ODataError" /> object.</summary>
 /// <param name="error">The <see cref="T:Microsoft.OData.Core.ODataError" /> instance representing the error read from the payload.</param>
 /// <remarks>
 /// The Message property is initialized to a system-supplied message
 /// that describes the error. This message takes into account the
 /// current system culture.
 /// </remarks>
 public ODataErrorException(ODataError error)
     : this(Strings.ODataErrorException_GeneralError, null, error)
 {
 }
Esempio n. 22
0
 /// <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 virtual Task WriteInStreamErrorAsync(ODataError error, bool includeDebugInformation)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
 }
Esempio n. 23
0
 /// <summary>Creates a new instance of the <see cref="T:Microsoft.OData.Core.ODataErrorException" /> class with an error message, an inner exception, and an <see cref="T:Microsoft.OData.Core.ODataError" /> object.</summary>
 /// <param name="message">The plain text error message for this exception.</param>
 /// <param name="innerException">The inner exception that is the cause of this exception to be thrown.</param>
 /// <param name="error">The <see cref="T:Microsoft.OData.Core.ODataError" /> instance representing the error read from the payload.</param>
 public ODataErrorException(string message, Exception innerException, ODataError error)
     : base(message, innerException)
 {
     this.state.ODataError = 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>
        /// <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();

            ODataAtomWriterUtils.WriteError(this.xmlWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth);
            this.Flush();
        }
        public override void Visit(ODataErrorPayload payloadElement)
        {
            ExceptionUtilities.Assert(this.items.Count == 0, "Error should only be top level");
            var error = new ODataError()
            {
                ErrorCode = payloadElement.Code,
                Message = payloadElement.Message
            };

            this.items.Push(error);
            base.Visit(payloadElement);
        }
        /// <summary>
        /// Converts an <see cref="ODataErrorpayload"/> into the corresponding <see cref="ODataError"/>.
        /// </summary>
        /// <param name="errorPayload">The error payload to convert.</param>
        /// <param name="forAtom">true if the conversion follows ATOM format rules; false for JSON format rules.</param>
        /// <returns>A new <see cref="ODataError"/> representing the <paramref name="errorPayload"/>.</returns>
        private static ODataError ConvertErrorPayload(ODataErrorPayload errorPayload, bool forAtom)
        {
            ODataError error = new ODataError();

            error.ErrorCode = errorPayload.Code;
            error.Message = errorPayload.Message; ;

            ODataInternalExceptionPayload innerErrorPayload = errorPayload.InnerError;
            if (innerErrorPayload != null)
            {
                error.InnerError = ConvertInnerErrorPayload(innerErrorPayload);
            }

            return error;
        }
 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;
 }
Esempio n. 28
0
 /// <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>
 public virtual void WriteError(ODataError error, bool includeDebugInformation)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Error);
 }
        /// <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);
            }
        }
Esempio n. 30
0
 /// <summary>Creates a new instance of the <see cref="T:Microsoft.OData.Core.ODataErrorException" /> class with an error message, an inner exception, and an <see cref="T:Microsoft.OData.Core.ODataError" /> object.</summary>
 /// <param name="message">The plain text error message for this exception.</param>
 /// <param name="innerException">The inner exception that is the cause of this exception to be thrown.</param>
 /// <param name="error">The <see cref="T:Microsoft.OData.Core.ODataError" /> instance representing the error read from the payload.</param>
 public ODataErrorException(string message, Exception innerException, ODataError error)
     : base(message, innerException)
 {
     this.state.ODataError = error;
 }
Esempio n. 31
0
        public void TestWriteError()
        {
            ODataError odataError = new ODataError()
            {
                ErrorCode = "404",
                Message = "Not Found",
            };

            MemoryStream ms = new MemoryStream();
            using (var omw = TestHelper.CreateMessageWriter(ms, "avro/binary", AvroMediaTypeResolver.Instance))
            {
                omw.WriteError(odataError, false);
            }

            ms.Seek(0, SeekOrigin.Begin);

            Error error;
            IAvroReader<Error> reader = null;
            using (reader = AvroContainer.CreateReader<Error>(ms))
            using (var seqReader = new SequentialReader<Error>(reader))
            {
                error = seqReader.Objects.First();
            }

            Assert.IsNotNull(error);
            Assert.AreEqual("404", error.ErrorCode);
            Assert.AreEqual("Not Found", error.Message);
        }
Esempio n. 32
0
 /// <summary>Creates a new instance of the <see cref="T:Microsoft.OData.Core.ODataErrorException" /> class with an error message and an <see cref="T:Microsoft.OData.Core.ODataError" /> object.</summary>
 /// <param name="message">The plain text error message for this exception.</param>
 /// <param name="error">The <see cref="T:Microsoft.OData.Core.ODataError" /> instance representing the error read from the payload.</param>
 public ODataErrorException(string message, ODataError error)
     : this(message, null, error)
 {
 }
Esempio n. 33
0
        /// <summary>Creates an ODataError instance describing the error.</summary>
        /// <returns>A new ODataError instance describing the error.</returns>
        internal ODataError CreateODataError()
        {
            ODataError error = new ODataError();
            DataServiceException dataException = this.Exception as DataServiceException;
            if (dataException == null)
            {
                error.ErrorCode = String.Empty;
                error.Message = Strings.DataServiceException_GeneralError;

                if (this.UseVerboseErrors)
                {
                    error.InnerError = new ODataInnerError(this.Exception);
                }
            }
            else
            {
                error.ErrorCode = dataException.ErrorCode ?? String.Empty;
                error.Message = dataException.Message ?? String.Empty;

                if (this.UseVerboseErrors && dataException.InnerException != null)
                {
                    error.InnerError = new ODataInnerError(dataException.InnerException);
                }
            }

            error.InstanceAnnotations = this.InstanceAnnotations;

            return error;
        }
        public void CreateErrorResponse_Respects_IncludeErrorDetail(IncludeErrorDetailPolicy errorDetail, bool? isLocal, bool? includeErrorDetail, bool detailIncluded)
        {
            HttpConfiguration config = new HttpConfiguration() { IncludeErrorDetailPolicy = errorDetail };
            HttpRequestMessage request = new HttpRequestMessage();
            request.SetConfiguration(config);
            if (isLocal.HasValue)
            {
                request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => isLocal.Value));
            }
            if (includeErrorDetail.HasValue)
            {
                request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy<bool>(() => includeErrorDetail.Value));
            }
            ODataError error = new ODataError()
            {
                ErrorCode = "36",
                Message = "Bad stuff",
                InnerError = new ODataInnerError()
                {
                    Message = "Exception message"
                }
            };

            HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.BadRequest, error);

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            ODataError contentError;
            Assert.True(response.TryGetContentValue<ODataError>(out contentError));
            Assert.Equal("36", contentError.ErrorCode);
            Assert.Equal("Bad stuff", contentError.Message);
            if (detailIncluded)
            {
                Assert.NotNull(contentError.InnerError);
                Assert.Equal("Exception message", contentError.InnerError.Message);
            }
            else
            {
                Assert.Null(contentError.InnerError);
            }
        }
Esempio n. 35
0
 public void InitTest()
 {
     this.odataError = new ODataError();
 }