【问题标题】:Error handling on DBI->connectDBI->connect 上的错误处理
【发布时间】:2011-10-02 17:30:33
【问题描述】:

除了使用标准代码 die "Unable to connect: $DBI::errstr\n" 处理错误之外,是否可以编写如下自定义代码?

标准:

$dbstore = DBI->connect($dsn, $user, $pw,
    {ora_session_mode => $mode, PrintError => 0, RaiseError => 0, AutoCommit => 0}) 
    or die "Unable to connect: $DBI::errstr\n";

自定义:

$dbstore = DBI->connect($dsn, $user, $pw,
    {ora_session_mode => $mode, PrintError => 0, RaiseError => 0, AutoCommit => 0});

if (!$dbstore)
{
    CUSTOM_LOG_HANDLER("Could not connect to database: $DBI::errstr");
    return;
}

示例标准代码:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

#DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";

# PERL DBI CONNECT (RENAMED HANDLE)
$dbstore = DBI->connect($dsn, $user, $pw) or die "Unable to connect: $DBI::errstr\n";

感谢您的宝贵时间。

【问题讨论】:

  • 有没有其他方法可以优雅地退出而不会出现错误登录到 Web 服务器日志?

标签: perl dbi


【解决方案1】:

您始终可以在 DBI 中使用自定义错误处理程序:

#!/usr/bin/perl

use strict;
use warnings;

use DBI;

sub handle_error {
    my $message = shift;
    #write error message wherever you want
    print "the message is '$message'\n";
    exit; #stop the program
}

my $dbh = DBI->connect(
    "dbi:SQLite:foo",
    "user",
    "pass",
    {
        PrintError  => 0,
        HandleError => \&handle_error,
    }
) or handle_error(DBI->errstr);

my $sth = $dbh->prepare("select * from doesntexist");

也就是说,您应该记录错误,对于 Web 应用程序,Web 服务器的日志是有意义的。如果您担心网络日志中的噪音量,您应该专注于修复错误,而不是通过删除信息源来减少日志噪音。

【讨论】:

  • 感谢您的帮助。 PrintError => 0, RaiseError => 1 的值应该是多少?
  • 示例此代码是否有效? $dbstore = DBI->connect($dsn, $user, $pw, {ora_session_mode => $mode, PrintError => 0, RaiseError => 1, AutoCommit => 0, HandleError => \&handle_error_and_exit}) 或 handle_error_and_exit("无法连接到 $user/$pw: $DBI::errstr");
  • RaiseError 默认是关闭的,如果你不想向 STDERR 发送消息,你应该关闭它。 PrintError 默认开启,这就是我关闭它的原因。在DBI documentation 中它说“如果子程序返回一个假值,那么 RaiseError 和/或 PrintError 属性会被检查并正常处理。”,只要函数返回一个真值(或exits) ,那么 PrintError 或 RaiseError 都不应该有任何影响。
猜你喜欢
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 2023-02-04
  • 2010-11-02
相关资源
最近更新 更多