Pergunta

First of all thanks for taking the time to read through my post. I have a question that may be a newbie piece of cake for some.

I am adding data to a database table using Entity Framework. When adding a duplicate Primary Key I get an exception in InnerException.Message that reads "Violation of PRIMARY KEY constraint 'PK_StudentID'. Cannot insert duplicate key in object 'dbo.Students'. The statement has been terminated. "

However, what I want to do is to rephrase this error message for the end user, but also save this exact message with the table name and column name to my logs for later. Essentially, I want to rephrase the error message to "You cannot have a duplicate entry for Student Identification Number. Please enter a new value."

How can I do this?

I have tried to inherit from System.Data.UpdateException and put an if check to see what the innerexception.message reads, and then change it accordingly. That did not work.

Thanks,

Foi útil?

Solução

I think this will do what you want.

        Try
            'your code
        Catch ex As Exception
            'store the ex.Message where you want

            Throw New Exception("Your custom message here.")
        End Try

Example:

Private Sub uiFunction()
    Dim errorMessage As String
    Try

        'a call to a BLL function/sub that could cause an exception
    Catch ex As Exception
        errorMessage = ex.Message() 'ex.Message() = "Your custom message."
    End Try
End Sub

Public Sub BLLFunction()
    Try
        'run your code that could cause an exception
    Catch ex As Exception
        Throw New Exception("Your custom message.")
    End Try
End Sub
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top