2017-11-29 29 views
1

RaiseError가 꺼져있는 것처럼 스크립트의 일부 섹션에서 Perl의 DBI HandleError 속성을 "해제"할 수 있습니까?PERL - 특정 섹션에서 DBI HandleError 비활성화

예 :

my $dbh = DBI->connect("DBI:SQLite:dbname=file.db","","",{ PrintError => 0, RaiseError => 0, 
                  HandleError => sub{ Log("ERROR: Something failed in db"); exit 1 } }) 
     or die "Couldn't connect"; 

for my $table (@db_tables){ 
    $dbh->do("delete from $table") 
      or do{ Log("ERROR: Delete failed"); next }; 

    Log("Table [$table] content was deleted"); 
} 

exit 0; 
여기

내가는 handleError 그 테이블 중 하나의 내용을 삭제할 수없는 이유만으로 스크립트를 죽이고 싶지 않습니다. 수동으로 오류를 처리하고 싶습니다.

+0

Try :: Tiny를 살펴보고 해당 섹션을 "try"블록에 넣는 것을 고려한 다음 나중에 원하는 경우 자체 오류 처리를 추가 할 수 있습니다. – AKHolland

답변

5

HandleError attribute은 항상 변경 될 수 있습니다. $dbh의 해시 참조로 이동하여 직접 액세스하므로 간단히 local 크기를 지정할 수 있습니다.

for my $table (@db_tables){ 
    local $dbh->{HandleError}; # it's now undef 
    $dbh->do("delete from $table") 
      or do{ Log("ERROR: Delete failed"); next }; 

    Log("Table [$table] content was deleted"); 
} 

더 나은 구현은 오류를 올바르게 처리하고 한 번만 현지화를 설정하는 것입니다. 이를 위해 루프 주변에 외부 범위를 만듭니다.

{ 
    local $dbh->{HandleError} = sub { 
     my (undef, $error) = @_ 
     Log("ERROR: Delete failed ($error)"); 
    }; 

    for my $table (@db_tables){ 
     $dbh->do("delete from $table") 
      and Log("Table [$table] content was deleted"); 
    } 
} 

두 경우 모두이 범위의 코드와 그 안에있는 범위가 실행되는 동안에 만 값이 대체됩니다. 범위가 끝나면 자동으로 복원됩니다.

+0

우수. 고맙습니다. RaiseError 특성으로 지역화해야한다고 생각 했어야합니다. – JohnnyLoo