Condividi tramite


Gestione degli errori nelle applicazioni gestite (SQL Server Compact)

In questo argomento vengono illustrati esempi di codice che descrivono l'utilizzo degli oggetti errore disponibili nel provider di dati per SQL Server Compact 3.5. Tali oggetti possono essere utilizzati per individuare e visualizzare gli errori del motore che si verificano in SQL Server Compact 3.5 durante l'esecuzione dei metodi dell'oggetto Replication, RemoteDataAccess o Engine.

Oggetto SqlCeException

Quando si verifica un errore del motore, viene creato un oggetto SqlCeException, che contiene l'oggetto SqlCeErrorCollection, in cui è presente una raccolta di oggetti SqlCeError, uno per ogni errore dell'eccezione. Per accedere direttamente all'oggetto SqlCeErrorCollection, è possibile utilizzare la proprietà SqlCeException.Errors. In ogni oggetto SqlCeError è presente una matrice dei parametri di errore che contiene informazioni dettagliate relative all'errore. Diversamente da SQL Server, SQL Server Compact 3.5 restituisce informazioni dettagliate su un errore come raccolta di parametri. Quando si creano messaggi di errore, è consigliabile utilizzare una serie di cicli FOR nidificati, in modo da recuperare tutti i parametri in ogni oggetto SqlCeError della raccolta.

Esempi

Nell'esempio seguente il metodo ShowSqlException individua un errore di eccezione del motore di SQL Server Compact 3.5. Questo oggetto SqlCeException viene passato al metodo ShowErrors, che visualizza tutti gli oggetti SSCEError presenti nell'oggetto SqlCeErrorCollection. Questo metodo riproduce a ciclo continuo tutti i parametri di errore per ogni errore.

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

Vedere anche

Altre risorse

Creazione di applicazioni per smart device (SQL Server Compact)

Creazione di applicazioni per computer desktop (SQL Server Compact)

Provider di dati gestito (SQL Server Compact)

Gestione degli errori nelle applicazioni native