4

您好我正在尝试进行一些异常处理并拦截重复的字段值(键违规)错误。从我寻找解决方案的过程中,我看到了许多使用以下方法捕获所有错误的建议

try
(enter code)
except on E: EDatabaseError do
showmessage (Error message);
end; 

但我想专门回应一个密钥违规,它使用一个使用 ADO 的访问表。

4

3 回答 3

7

如果您要处理的唯一错误是带有“重复值”消息的错误,这将起作用:

try
  // Your code
except
  on E: EOleException do
  begin
    // The better way is to find out what E.ErrorCode is
    // for this specific exception, and handle it instead
    // of checking the string - you didn't provide the
    // ErrorCode, though.
    // If E.ErrorCode = <whatever> then
    //
    if Pos('duplicate value', E.Message) > 0 then
      // You've got a duplicate with the message above
      // Do whatever handles it
    else
      raise;
  end;
  // If you want to handle other exception types (eg., EDataBaseError),
  // you can do so here:
  //  on E: EDataBaseError do
  //    HandleDBError;
end;
于 2012-04-15T20:43:26.693 回答
6

EDatabaseError只是一个通用的 excption 类,没有关于错误的附加信息,要在 ADO 中获取有关错误的扩展信息,您必须在引发异常时使用该属性TADOConnection.Errors来获取特定的错误代码Key violation,为此检查NumberNativeError属性。

您可以在此处找到有关此主题的更多文档

于 2012-04-15T21:28:30.530 回答
3

从您的描述来看,这听起来不像是您应该让其成为例外的事情。特别是如果你要做的就是EOleException. 例外情况应该是您没有好的方法来处理的事情,而这里不是这种情况。

我建议您在尝试添加新记录之前检查新 ID 是否尚未使用。或者,正如@TLama 建议的那样,利用数据库框架的任何错误处理工具,让您在它成为异常之前挂钩它。

于 2012-04-15T20:48:42.633 回答