Manipulando erros em aplicativos gerenciados (SQL Server Compact)

Este tópico fornece exemplos de código que mostram como usar os objetos de erro fornecidos pelo Provedor de Dados para SQL Server Compact. Você pode usar esses objetos para capturar e exibir erros de mecanismo que ocorrem no SQL Server Compact ao executar métodos dos objetos Engine.

O objeto SqlCeException

Quando ocorre um erro do mecanismo, um objeto SqlCeException é criado. Este objeto de exceção contém o objeto SqlCeErrorCollection. Ele, por sua vez, contém uma coleção de objetos SqlCeError, um para cada erro da exceção. O objeto SqlCeErrorCollection pode ser acessado diretamente usando a propriedade SqlCeException.Errors. Cada objeto SqlCeError contém uma matriz de parâmetros de erro que fornecem informações detalhadas sobre o erro. Diferentemente do SQL Server, o SQL Server Compact retorna informações detalhadas sobre um erro como uma coleção de parâmetros. Ao criar mensagens de erro, é recomendável usar uma série de loops FOR aninhados para recuperar cada parâmetro em cada objeto SqlCeError da coleção.

Exemplos

No exemplo a seguir, o método ShowSqlException captura um erro de exceção do mecanismo do SQL Server Compact. Esse objeto SqlCeException é passado para o método ShowErrors. Isso exibe cada um dos objetos SSCEError no objeto SqlCeErrorCollection. Este método faz um loop por todos os parâmetros de cada erro.

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

Consulte também

Referência

Provedor de dados gerenciado (SQL Server Compact)

Manipulando erros em aplicativos nativos

Conceitos

Criando aplicativos da área de trabalho (SQL Server Compact)