Чистый способ отловить ошибки из таблицы Azure (кроме соответствия строк?) - PullRequest
4 голосов
/ 18 сентября 2010

Я хотел бы получить список всех ошибок в таблице Azure и найти простой способ их обработки в блоке try...catch.

Например, я бы не хотелнепосредственно кодируйте и сравните сообщение InnerException с String.Contains("The specified entity already exists").Как правильно ловить эти ошибки?

alt text

Ответы [ 4 ]

3 голосов
/ 08 июля 2011

Для обработки ошибок при добавлении объектов в таблицу вы можете использовать следующий код:

try {
  _context.AddObject(TableName, entityObject);
  _context.SaveCangesWithRetries(); 
}
catch(DataServiceRequestException ex) {
  ex.Response.Any(r => r.StatusCode == (int)System.Net.HttpStatusCode.Conflict) 
  throw;
}

Как сказано в другом ответе, список ошибок TableStorage можно найти по адресу: http://msdn.microsoft.com/en-us/library/dd179438.aspx

3 голосов
/ 18 сентября 2010

Вы можете попытаться посмотреть на значения в ответе, а не на внутреннее исключение.Это пример одного из моих блоков try catch:

try {
    return query.FirstOrDefault();
}
catch (System.Data.Services.Client.DataServiceQueryException ex)
{
    if (ex.Response.StatusCode == (int)System.Net.HttpStatusCode.NotFound) {
        return null;
    }
    throw;
}

Очевидно, это просто потому, что элемент не существует, но я уверен, что вы можете расширить эту концепцию, взглянув на список кодов ошибок Azure .

2 голосов
/ 18 сентября 2010

См. Мой код здесь: http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob. Шаблон должен перехватить StorageClientException, а затем использовать свойство .ErrorCode для сопоставления с константами в StorageErrorCode.

1 голос
/ 19 сентября 2010

Вот код, предоставленный в Таблице Azure White Paper , но я не уверен, дает ли это какое-либо значение в ответе smark.

   /*
         From Azure table whitepaper

         When an exception occurs, you can extract the sequence number (highlighted above) of the command that caused the transaction to fail as follows:

try
{
    // ... save changes 
}
catch (InvalidOperationException e)
{
    DataServiceClientException dsce = e.InnerException as DataServiceClientException;
    int? commandIndex;
    string errorMessage;

    ParseErrorDetails(dsce, out commandIndex, out errorMessage);
}


          */

-

    void ParseErrorDetails( DataServiceClientException e, out string errorCode, out int? commandIndex, out string errorMessage)
    {

        GetErrorInformation(e.Message, out errorCode, out errorMessage);

        commandIndex = null;
        int indexOfSeparator = errorMessage.IndexOf(':');
        if (indexOfSeparator > 0)
        {
            int temp;
            if (Int32.TryParse(errorMessage.Substring(0, indexOfSeparator), out temp))
            {
                commandIndex = temp;
                errorMessage = errorMessage.Substring(indexOfSeparator + 1);
            }
        }
    }

    void GetErrorInformation(  string xmlErrorMessage,  out string errorCode, out string message)
    {
        message = null;
        errorCode = null;

        XName xnErrorCode = XName.Get("code", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
        XName xnMessage = XName.Get  ( "message",    "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");

        using (StringReader reader = new StringReader(xmlErrorMessage))
        {
            XDocument xDocument = null;
            try
            {
                xDocument = XDocument.Load(reader);
            }
            catch (XmlException)
            {
                // The XML could not be parsed. This could happen either because the connection 
                // could not be made to the server, or if the response did not contain the
                // error details (for example, if the response status code was neither a failure
                // nor a success, but a 3XX code such as NotModified.
                return;
            }

            XElement errorCodeElement =   xDocument.Descendants(xnErrorCode).FirstOrDefault();

            if (errorCodeElement == null)
            {
                return;
            }

            errorCode = errorCodeElement.Value;

            XElement messageElement =   xDocument.Descendants(xnMessage).FirstOrDefault();

            if (messageElement != null)
            {
                message = messageElement.Value;
            }
        }
    }
...