如何抑制来自 DBI 的任意警告/错误消息?
代码:
# A:
$dbh->do(qq/insert into foo(cl) values('test')/);
# B:
$dbh->do(qq/insert into foo(cl) values('test')/) or warn $dbh->errstr;
# C:
eval { $dbh->do(qq/insert into foo(cl) values('test')/); };
warn "error : $@ " if $@;
全部都会输出:
DBD::mysql::db do failed: Duplicate entry 'test' for key 'cl' at a.pl line 9.
我不希望将此任意警告/错误消息发送到 stderr。我想使用warn $dbh->errstr
。
perl a.pl 2>/dev/null
会抑制错误消息,但我想知道如何在脚本中执行此操作?
code:
# A:
$dbh->do(qq/insert into foo(cl) values('test')/);
# B:
$dbh->do(qq/insert into foo(cl) values('test')/) or warn $dbh->errstr;
# C:
eval { $dbh->do(qq/insert into foo(cl) values('test')/); };
warn "error : $@ " if $@;
All would output :
DBD::mysql::db do failed: Duplicate entry 'test' for key 'cl' at a.pl line 9.
I dont want this arbitrary warning/error message send to stderr. I'd like use warn $dbh->errstr
.
perl a.pl 2>/dev/null
would suppress the error message, but I want to know how to do this in script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要安装自己的错误处理程序。例如,
错误处理程序在 DBI POD 中进行了描述。
另一个选项是:
设置
PrintWarn
属性设置为 false 值(由 Sinan 在某些论坛上的回答提供通过信号处理程序捕获所有警告:
$SIG{'__WARN__'} = sub {};
You need to install your own error handler. E.g.
Error handlers are described in DBI POD
Another options are to:
Set
PrintWarn
attribute to false value (courtesy of Sinan's answer on some forumTrap all warnings via a signal handler:
$SIG{'__WARN__'} = sub {};
如今,我通常会执行以下操作
RaiseError => 1、
打印错误=> 0 创建 DBI 句柄时。现在您不必向每个 DBI 调用添加错误处理程序。
对于我不关心重复键错误的语句,捕获并忽略该异常:
这是我发现的最好方法 -
INSERT IGNORE
忽略all< /em> 错误,而不仅仅是重复键错误,并且REPLACE
将使用删除和插入覆盖现有行。可能会使用 INSERT INTO ... ON DUPLICATE KEY UPDATE id=id ,但我认为捕获错误更明确。Nowadays I typically do the following
RaiseError => 1
,PrintError => 0
when creating a DBI handle. Now you don't have to add an error handler to every DBI call.For statements where I am unconcerned about Duplicate key errors, catch and ignore that exception:
This is the best way I've found -
INSERT IGNORE
ignores all errors, not just duplicate key errors, andREPLACE
will overwrite the existing row using a delete and insert.INSERT INTO ... ON DUPLICATE KEY UPDATE id=id
could possibly used, but I think catching the error is more explicit.