Pregunta

Me gustaría obtener una lista de todos los errores Azure tabla y figura a cabo de una manera limpia para manejarlos en un bloque try...catch.

Por ejemplo, me gustaría no tener que directamente código y comparar el mensaje InnerException a String.Contains("The specified entity already exists"). ¿Cuál es la manera correcta para atrapar estos errores?

text alt

¿Fue útil?

Solución 4

Aquí está el código que se proporciona en el Azure Tabla Whitepaper , pero no estoy seguro de si esto da ningún valor sobre la respuesta de 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;
            }
        }
    }

Otros consejos

Se podría intentar buscar en los valores de la respuesta, más bien que la excepción interna. Este es un ejemplo de uno de mis bloques catch try:

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

Es evidente que esto es sólo para el elemento no existe error, pero estoy seguro de que pueden ampliar en este concepto por mirar el lista de códigos de error Azure .

Para controlar los errores al tiempo que añade objetos a una tabla se puede utilizar el siguiente código:

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

Como se dijo en otra respuesta se puede encontrar una lista de errores TableStorage en: http : //msdn.microsoft.com/en-us/library/dd179438.aspx

Vea mi código aquí: http: // blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob . El patrón es coger un StorageClientException, y luego utilizar la propiedad para que coincida con .ErrorCode contra las constantes en StorageErrorCode.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top