0

首先感谢您花时间阅读我的帖子。我有一个问题,对某些人来说可能是小菜一碟。

我正在使用实体框架将数据添加到数据库表中。添加重复的主键时,我在 InnerException.Message 中出现异常,显示“违反主键约束 'PK_StudentID'。无法在对象 'dbo.Students' 中插入重复键。语句已终止。”

但是,我想做的是为最终用户重新表述此错误消息,但还要将此带有表名和列名的确切消息保存到我的日志中以供以后使用。本质上,我想将错误消息改写为“您不能有重复的学生识别号条目。请输入一个新值。”

我怎样才能做到这一点?

我试图从 System.Data.UpdateException 继承并进行 if 检查以查看 innerexception.message 读取的内容,然后相应地进行更改。那没有用。

谢谢,

4

1 回答 1

0

我认为这会做你想要的。

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

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

例子:

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
于 2011-04-29T13:30:17.767 回答