Share via


Tratar errores en aplicaciones administradas (SQL Server Compact)

En este tema se ofrecen ejemplos de código que muestran cómo usar los objetos de error proporcionados por el proveedor de datos para SQL Server Compact. Estos objetos pueden usarse para capturar y mostrar errores del motor que se producen en SQL Server Compact al ejecutar los métodos del objeto Engine.

El objeto SqlCeException

Cuando se produce un error del motor, se crea un objeto SqlCeException. Este objeto de excepción contiene el objeto SqlCeErrorCollection. A su vez, este objeto contiene una colección de objetos SqlCeError, uno por cada error de la excepción. Se puede obtener acceso directamente al objeto SqlCeErrorCollection mediante la propiedad SqlCeException.Errors. Cada objeto SqlCeError contiene una matriz de parámetros de error que proporcionan información detallada acerca del error. A diferencia de SQL Server, SQL Server Compact devuelve información detallada acerca de un error en forma de colección de parámetros. Al generar mensajes de error, se recomienda que utilice una serie de bucles FOR anidados para recuperar cada parámetro de cada objeto SqlCeError de la colección.

Ejemplos

En el siguiente ejemplo, el método ShowSqlException detecta un error de excepción del motor de SQL Server Compact. Este objeto SqlCeException se pasa al método ShowErrors. Éste muestra cada uno de los objetos SSCEError en el objeto SqlCeErrorCollection. Este método pasa por todos los parámetros de error para cada error.

C#

// Reference the data provider.
using System.Data.SqlServerCe;

// Start the method to generate a database engine exception.
public void ShowSqlCeException() 
{
    string mySelectQuery = "SELECT column1 FROM table1";
    SqlCeConnection myConnection = new SqlCeConnection("Data Source=nonExistSource.sdf;");
    SqlCeCommand myCommand = new SqlCeCommand(mySelectQuery,myConnection);

    try 
    {
        myCommand.Connection.Open();
    }

    // Catch the exception as e and pass it to the ShowErrors routine.
    catch (SqlCeException e) 
    {
        ShowErrors(e);
    }

}

// Error handling routine that generates an error message
public static void ShowErrors(SqlCeException e) 
{
    SqlCeErrorCollection errorCollection = e.Errors;

    StringBuilder bld = new StringBuilder();
    Exception inner = e.InnerException;

    if (null != inner) 
    {
        MessageBox.Show("Inner Exception: " + inner.ToString());
    }
    // Enumerate the errors to a message box.
    foreach (SqlCeError err in errorCollection) 
    {
        bld.Append("\n Error Code: " + err.HResult.ToString("X")); 
        bld.Append("\n Message   : " + err.Message);
        bld.Append("\n Minor Err.: " + err.NativeError);
        bld.Append("\n Source    : " + err.Source);

        // Enumerate each numeric parameter for the error.
        foreach (int numPar in err.NumericErrorParameters) 
        {
            if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
        }

        // Enumerate each string parameter for the error.
        foreach (string errPar in err.ErrorParameters) 
        {
            if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
        }

        MessageBox.Show(bld.ToString());
        bld.Remove(0, bld.Length);
    }
}

Visual Basic

' Reference the data provider by using the Imports directive.
Imports System.Data.SqlServerCe

' Start the method to generate a database engine exception.
Public Sub ShowSqlCeException()
    Dim mySelectQuery As String = "SELECT column1 FROM table1"
    Dim myConnection As New SqlCeConnection("Data Source=nonExistSource.sdf;")
    Dim myCommand As New SqlCeCommand(mySelectQuery, myConnection)

    Try
        myCommand.Connection.Open()

    ' Catch the exception as e and pass it to the ShowErrors routine.
    Catch e As SqlCeException

        ShowErrors(e)

    End Try
End Sub

' Error handling routine that generates an error message
Public Shared Sub ShowErrors(ByVal e As SqlCeException)
    Dim errorCollection As SqlCeErrorCollection = e.Errors

    Dim bld As New StringBuilder()
    Dim inner As Exception = e.InnerException

    If Not inner Is Nothing Then
        MessageBox.Show(("Inner Exception: " & inner.ToString()))
    End If

    Dim err As SqlCeError

    ' Enumerate each error to a message box.
    For Each err In errorCollection
        bld.Append((ControlChars.Cr & " Error Code: " & err.HResult.ToString("X")))
        bld.Append((ControlChars.Cr & " Message   : " & err.Message))
        bld.Append((ControlChars.Cr & " Minor Err.: " & err.NativeError))
        bld.Append((ControlChars.Cr & " Source    : " & err.Source))

        ' Retrieve the error parameter numbers for each error.
        Dim numPar As Integer
        For Each numPar In err.NumericErrorParameters
            If 0 <> numPar Then
                bld.Append((ControlChars.Cr & " Num. Par. : " & numPar))
            End If
        Next numPar

        ' Retrieve the error parameters for each error.
        Dim errPar As String
        For Each errPar In err.ErrorParameters
            If [String].Empty <> errPar Then
                bld.Append((ControlChars.Cr & " Err. Par. : " & errPar))
            End If
        Next errPar

        MessageBox.Show(bld.ToString())
        bld.Remove(0, bld.Length)
    Next err
End Sub

Vea también

Referencia

Proveedor de datos administrados (SQL Server Compact)

Control de errores en las aplicaciones nativas

Conceptos

Compilar aplicaciones para equipos de escritorio (SQL Server Compact)