public void When_Querying_For_NonExistent_EntitySet_Then_Throw_DataServiceQueryException_With_NotFound_Status_Code() { using (var scenario = new ODataScenario() .WithProducts(Any.Products()) .Start()) { var context = GetDataServiceContext(scenario.GetBaseAddress()); var action = new Action(() => { var dQuery = context.CreateQuery <Product>("/" + "RandomEntitySet"); var products = context.ExecuteAsync <Product, IProduct>(dQuery).Result; }); //check for AggregateException with DataServiceQueryException as InnerException. //Also retrieve the DataServiceQueryException InnerException. DataServiceQueryException innerException = action.ShouldThrow <AggregateException>() .WithInnerException <DataServiceQueryException>() .And.InnerException as DataServiceQueryException; //Check for 'Not Found' code. innerException.Response.StatusCode.Should().Be(404); } }
private void ProcessDataServiceQuery(DataServiceQueryException dsqe) { /*this.errorMessage = dsqe.Message; */ if (dsqe.Response != null) { this.statusCode = dsqe.Response.StatusCode; } if (dsqe.InnerException != null) { string jsonResponse = dsqe.InnerException.Message; // Some messages are not json formatted // check the exact format! (Java vs .Net) try { ODataServiceSdlResponse response = JsonConvert.DeserializeObject <ODataServiceSdlResponse>(jsonResponse); this.errorMessage = response.Error.Message; if (response.Error.InnerMessage != null) { this.errorExtraMessage = response.Error.InnerMessage.Message; } } catch (Exception jsonEx) { this.errorMessage = jsonResponse; } } else { this.errorMessage = dsqe.Message; } }
internal static TableServiceExceptionAction ProcessTableServiceQueryException(FabricEvents.ExtensionsEvents traceSource, string logSourceId, Exception e, TableServiceAction failedAction) { traceSource.WriteError( logSourceId, "Exception encountered when performing operation {0}. Exception information: {1}", failedAction, e); DataServiceQueryException eDataServiceQuery = e as DataServiceQueryException; if (null != eDataServiceQuery) { if (Utility.IsNetworkError(eDataServiceQuery.Response.StatusCode)) { // We encountered a network error that wasn't resolved even // after retries. throw new MaxRetriesException(); } else { return(TableServiceExceptionAction.Abort); } } StorageException eStorage = e as StorageException; if (null != eStorage) { return(ProcessStorageException(eStorage)); } return(TableServiceExceptionAction.Abort); }
// HACK: just duplicating the other overload of 'GetErrorCode' /// <summary>Hack around lack of proper way of retrieving the error code through a property.</summary> public static string GetErrorCode(DataServiceQueryException ex) { var r = new Regex(@"<code>(\w+)</code>", RegexOptions.IgnoreCase); var match = r.Match(ex.InnerException.Message); return(match.Groups[1].Value); }
public void When_Querying_For_Non_Existent_EntityType_Then_Throw_Exception() { using (var scenario = new ODataScenario() .WithProducts(Any.Products()) .Start()) { var context = GetDataServiceContext(scenario.GetBaseAddress()); var action = new Action(() => { //query for a missing product based on the 'Id' var dQuery = context.CreateQuery <Product>("/" + "Products(7)"); // this should ideally return null or thrown an exception that reflects 404. Product missingProd = context.ExecuteSingleAsync <Product, IProduct>(dQuery).Result as Product; //Product missingProd = dQuery.Where(p => p.Id == 7).First(); }); //check for AggregateException with DataServiceQueryException as InnerException. //Also retrieve the DataServiceQueryException InnerException. DataServiceQueryException innerException = action.ShouldThrow <AggregateException>() .WithInnerException <DataServiceQueryException>() .And.InnerException as DataServiceQueryException; //Check for 'Not Found' code. innerException.Response.StatusCode.Should().Be(404); } }
/// <summary> /// Extracts the server error message from a client side query exception. /// </summary> /// <param name="exception">The DataService Query exception to extract error message from.</param> /// <returns>The server error message.</returns> public static string ExtractServerErrorMessage(DataServiceQueryException exception) { string contentType = exception.Response.Headers[HttpHeaders.ContentType]?.Replace(" ", string.Empty); var innerException = exception.InnerException as DataServiceClientException; ExceptionUtilities.Assert(innerException != null, "No inner exception on query exception"); return(GetErrorMessage(innerException, contentType)); }
public void WebRequestTransientErrorDetectionStrategyTestDataServiceQueryException() { // Unfortunately this exception isn't easy to Mock with an actual error code so just // do a basic test var exception = new DataServiceQueryException("Simulated DataServiceQueryException"); bool actual = new WebRequestTransientErrorDetectionStrategy().IsTransient(exception); Assert.IsFalse(actual); }
public ODataError(Exception ex) { if (ex == null) { throw new ArgumentNullException(); } Type errorType = ex.GetType(); // Awful code if (ex is DataServiceRequestException) { DataServiceRequestException dsre = ex as DataServiceRequestException; this.ProcessDataServiceRequest(dsre); return; } if (ex is DataServiceClientException) { DataServiceClientException dsce = ex as DataServiceClientException; this.ProcessDataServiceClient(dsce); return; } if (ex is DataServiceTransportException) { DataServiceTransportException dste = ex as DataServiceTransportException; this.ProcessDataServiceTransport(dste); return; } if (ex is DataServiceQueryException) { DataServiceQueryException dsqe = ex as DataServiceQueryException; this.ProcessDataServiceQuery(dsqe); return; } if (ex is InvalidOperationException) { InvalidOperationException inoper = ex as InvalidOperationException; this.ProcessInvalidOperation(inoper); return; } if (ex is NotImplementedException) { NotImplementedException notimpl = ex as NotImplementedException; this.ProcessNotImplemented(notimpl); return; } }
private static string ExtractMessageFromClientException(Exception exception) { DataServiceQueryException exception2 = exception as DataServiceQueryException; if ((exception2 != null) && (exception2.InnerException != null)) { XDocument document; DataServiceClientException innerException = exception2.InnerException as DataServiceClientException; if ((exception2 != null) && (XmlUtility.TryParseDocument(innerException.Message, out document) && document.Root.Name.LocalName.Equals("error", StringComparison.OrdinalIgnoreCase))) { return(document.Root.GetOptionalElementValue("message", null)); } } return(null); }
public void AzureTableErrorCode_ResourceNotFound() { string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" + "<error xmlns=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">" + "<code>ResourceNotFound</code>" + "<message xml:lang=\"en-US\">The specified resource does not exist." + "RequestId:23e7a3b9-3d08-4461-ba49-737c9c211142" + "Time:2013-10-10T17:35:59.7597108Z</message>" + "</error>"; var clientExc = new DataServiceClientException(xml); bool isTableStorageDataNotFound = AzureStorageUtils.TableStorageDataNotFound(clientExc); Assert.IsTrue(isTableStorageDataNotFound, "Is TableStorageDataNotFound " + clientExc); var clientWrapped1 = new AggregateException(clientExc); isTableStorageDataNotFound = AzureStorageUtils.TableStorageDataNotFound(clientWrapped1); Assert.IsTrue(isTableStorageDataNotFound, "Is TableStorageDataNotFound " + clientWrapped1); var clientWrapped2 = new OrleansException("client", clientExc); isTableStorageDataNotFound = AzureStorageUtils.TableStorageDataNotFound(clientWrapped2); Assert.IsTrue(isTableStorageDataNotFound, "Is TableStorageDataNotFound " + clientWrapped2); var clientWrapped3 = new DataServiceQueryException("QueryException", clientExc); isTableStorageDataNotFound = AzureStorageUtils.TableStorageDataNotFound(clientWrapped3); Assert.IsTrue(isTableStorageDataNotFound, "Is TableStorageDataNotFound " + clientWrapped3); var clientWrapped4 = new DataServiceQueryException("Wrapped-clientWrapper1", clientWrapped1); isTableStorageDataNotFound = AzureStorageUtils.TableStorageDataNotFound(clientWrapped4); Assert.IsTrue(isTableStorageDataNotFound, "Is TableStorageDataNotFound " + clientWrapped4); var superWrapped1 = new DataServiceQueryException("SuperWrapped-Client4", new AggregateException("Wrapper5", clientWrapped4)); isTableStorageDataNotFound = AzureStorageUtils.TableStorageDataNotFound(superWrapped1); Assert.IsTrue(isTableStorageDataNotFound, "Is TableStorageDataNotFound " + superWrapped1); }
internal bool HandleException(Exception exception) { Nullable <HttpStatusCode> httpStatusCode = null; DataServiceRequestException requestException = exception as DataServiceRequestException; if (requestException != null) { OperationResponse opResponse = requestException.Response.FirstOrDefault(); httpStatusCode = opResponse != null ? (HttpStatusCode)opResponse.StatusCode : (HttpStatusCode)requestException.Response.BatchStatusCode; } DataServiceClientException clientException = exception as DataServiceClientException; if (!httpStatusCode.HasValue && clientException != null) { httpStatusCode = (HttpStatusCode)clientException.StatusCode; } DataServiceQueryException queryException = exception as DataServiceQueryException; if (!httpStatusCode.HasValue && queryException != null) { httpStatusCode = (HttpStatusCode)queryException.Response.StatusCode; } ODataErrorException odataException = exception as ODataErrorException; if (!httpStatusCode.HasValue && odataException != null) { var _errorCode = odataException.Error; } if (exception is AdalException || exception is ODataErrorException) { return(false); } return(true); }
public void StorageTransientErrorDetectionStrategyDataServiceClientExceptionTestByErrorString() { List <String> allStorageErrorCodeStrings = GetAllStorageErrorStringConstants(); StorageTransientErrorDetectionStrategy strategy = new StorageTransientErrorDetectionStrategy(); foreach (string errorString in allStorageErrorCodeStrings) { var innerException = new Exception(FormatErrorString(errorString)); var exception = new DataServiceQueryException("Simulated DataServiceQueryException", innerException); if (strategy.IsTransient(exception)) { Assert.IsTrue(SupportedRetryableStorageErrorStrings.Contains(errorString)); } else { Assert.IsFalse(SupportedRetryableStorageErrorStrings.Contains(errorString)); } } }
private static void ReportODataError(DataServiceQueryException ex) { //Client level Exception message Console.WriteLine(ex.Message); //The InnerException of DataServiceQueryException contains DataServiceClientException DataServiceClientException dataServiceClientException = ex.InnerException as DataServiceClientException; // You can get ODataErrorException from dataServiceClientException.InnerException // This object holds Exception as thrown from the service // ODataErrorException contains odataErrorException.Message contains a message string that conforms to dotnet // Exception.Message standards var odataErrorException = dataServiceClientException.InnerException as Microsoft.OData.ODataErrorException; if (odataErrorException != null) { Console.WriteLine(odataErrorException.Message); } Console.WriteLine(dataServiceClientException.Message); }
private static bool IsResourceNotFoundError(DataServiceQueryException ex) { return(ex.InnerException is DataServiceClientException && ((DataServiceClientException)ex.InnerException).StatusCode == 404); }
internal static void PreprocessObjectToWrite(ref object objectToWrite, ObjectGraphInfo info) { if (objectToWrite is DataServiceQuery) { objectToWrite = ((DataServiceQuery)objectToWrite).Execute(); } if (objectToWrite is QueryOperationResponse) { QueryOperationResponse qor = (QueryOperationResponse)objectToWrite; if (qor.GetType().IsGenericType&& (qor.GetType().GetGenericTypeDefinition() == typeof(QueryOperationResponse <>))) { objectToWrite = Util.VerticalRun(new object[] { new QueryOperationResponseWrapper(true, qor), new QueryOperationResponseWrapper(false, qor) }); } } else if (objectToWrite is QueryOperationResponseWrapper) { QueryOperationResponseWrapper wrapper = (QueryOperationResponseWrapper)objectToWrite; if (wrapper.Enumerate) { objectToWrite = wrapper.Qor; } else { DataServiceQueryContinuation continuation = wrapper.Qor.GetContinuation(); if (!((continuation == null) || wrapper.ElementType.Name.Contains <char>('<'))) { Uri nextLinkUri = continuation.NextLinkUri; objectToWrite = new Hyperlinq(QueryLanguage.Expression, "Execute<" + wrapper.ElementType.Name + "> (new Uri (\"" + nextLinkUri.ToString() + "\"))", "Next Page"); } else { objectToWrite = info.DisplayNothingToken; } } } else { DataServiceQueryException exception = objectToWrite as DataServiceQueryException; if ((exception != null) && (exception.InnerException is DataServiceClientException)) { DataServiceClientException innerException = (DataServiceClientException)exception.InnerException; try { XElement element = XElement.Parse(innerException.Message); if (element.Name.LocalName == "error") { XNamespace namespace2 = element.Name.Namespace; string str = (string)element.Element((XName)(namespace2 + "message")); if (!string.IsNullOrEmpty(str)) { str = str.Trim(); if (str.EndsWith("cannot be used in a query")) { str = str + " predicate"; } if (!str.EndsWith(".")) { str = str + "."; } Util.Highlight(str + " See exception below for more details.").Dump <object>(); } } } catch { } } } }
public static bool IsTablesNotFoundException(this DataServiceQueryException ex) { return(ex.InnerException != null && ex.InnerException is DataServiceClientException && ((DataServiceClientException)ex.InnerException).StatusCode == 404); }
protected override bool CheckIsTransient(Exception ex) { if (IsRetriableWebException(ex, operationIdempotentOnRetry: true, retryOnUnauthorizedErrors: true)) { return(true); } DataServiceRequestException dataServiceException = ex as DataServiceRequestException; if (dataServiceException != null) { if (IsErrorStringMatch(GetErrorCode(dataServiceException), StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return(true); } } DataServiceQueryException dataServiceQueryException = ex as DataServiceQueryException; if (dataServiceQueryException != null) { if (IsErrorStringMatch(GetErrorCode(dataServiceQueryException), StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return(true); } } DataServiceClientException dataServiceClientException = ex.FindInnerException <DataServiceClientException>(); if (dataServiceClientException != null) { if (IsRetriableHttpStatusCode(dataServiceClientException.StatusCode, operationIdempotentOnRetry: true, retryOnUnauthorizedErrors: true)) { return(true); } if (IsErrorStringMatch(dataServiceClientException.Message, StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return(true); } } var serverException = ex as StorageException; if (serverException != null) { if (IsErrorStringMatch(serverException, StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return(true); } } if (IsTimeoutException(ex)) { return(true); } if (IsSocketException(ex)) { return(true); } if ((ex.FindInnerException <IOException>() != null) && !(ex is FileLoadException)) { return(true); } return(false); }
/// <summary> /// Translates the data service exception. /// </summary> /// <param name="e">The exception.</param> /// <param name="reqResult">The request result.</param> /// <param name="parseError">The delegate used to parse the error to get extended error information.</param> /// <returns> /// The translated exception. /// </returns> internal static StorageException TranslateDataServiceException(Exception e, RequestResult reqResult, Func <Stream, IDictionary <string, string>, StorageExtendedErrorInformation> parseError) { try { // The exception thrown is based on whether it is a change/query operation. DataServiceRequestException dsre = FindInnerExceptionOfType <DataServiceRequestException>(e); DataServiceQueryException dsqe = FindInnerExceptionOfType <DataServiceQueryException>(e); if (dsre == null && dsqe == null) { InvalidOperationException ioe = TableUtilities.FindInnerExceptionOfType <InvalidOperationException>(e); if (ioe != null && !(ioe is WebException) && string.CompareOrdinal(ioe.Source, "Microsoft.Data.Services.Client") == 0 && ioe.Message.Contains("type is not compatible with the expected")) { return(new StorageException(reqResult, e.Message, e) { IsRetryable = false }); } return(null); } else if (dsre != null) { DataServiceResponse response = dsre.Response; // Get the batch status code first in case batch does not contain any responses. reqResult.HttpStatusCode = response.BatchStatusCode; IDictionary <string, string> headers; foreach (OperationResponse operationResponse in response) { reqResult.HttpStatusCode = operationResponse.StatusCode; // The exception thrown will contain the first error in the group of requests. if (reqResult.HttpStatusCode >= 300) { headers = operationResponse.Headers; // Strip off the extra exception type at the beginning. string innerException = dsre.InnerException.ToString().Replace("System.Data.Services.Client.DataServiceClientException: ", string.Empty); using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(innerException))) { reqResult.ExtendedErrorInformation = parseError(stream, headers); } break; } } return(new StorageException( reqResult, reqResult.ExtendedErrorInformation != null ? reqResult.ExtendedErrorInformation.ErrorCode : dsre.Message, dsre)); } else { QueryOperationResponse response = dsqe.Response; reqResult.HttpStatusCode = response.StatusCode; string innerException = dsqe.InnerException.Message; using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(innerException))) { reqResult.ExtendedErrorInformation = parseError(stream, response.Headers); } return(new StorageException( reqResult, reqResult.ExtendedErrorInformation != null ? reqResult.ExtendedErrorInformation.ErrorCode : dsqe.Message, dsqe)); } } catch (Exception) { return(new StorageException(reqResult, e.Message, e)); } }