end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

perlのDBIx::Class (DBIC)における例外処理( throw / catch )

どうやら、eval{}; で囲んで、$@ の有無でエラー確認することがお作法のようです。

my $schema = $self->db;  #読取り専用ユーザで確認しました
my $result_set = $schema->resultset('TestTable')->search()->slice(0,1);
my $tbl_row = $result_set->next();

eval{ $tbl_row->update({test_key=>'HOGE1'}) };
if ($@) {
    $self->error( $@ );  #Log4perl
    return undef;
}

ちなみに、DBIsqlを直接発行する場合は以下の通りで、execute()がnullを返すので、エラーメッセージを errstr() で受け取ることができます。

my $sql =<<EOF;
update test_table  set test_key=?  where test_id=?
EOF
my $sth = $self->{dbi}->prepare($sql);
my @val = ('HOGE1','ID1');
unless($sth->execute(@val)){
    self->error($sth->errstr);
    return undef;
}