2012-10-02 10 views

答えて

8

いいえ、キャッチすることはできません。unserialize()は例外をスローしません。

渡された文字列が直列化不能でない場合、FALSEが返され、E_NOTICEが発行されます。

あなたはすべてのエラーを処理するためのカスタム例外ハンドラを設定することができます。

function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 
3

は例外にすべてのPHPエラー(警告の通知など)を変換します。例はhereです。

$ret = @unserialize($foo); 
if($ret === null){ 
    //Error case 
} 

しかし、それは最も近代的なソリューションではありません。

9

簡単な方法があります。

上記のように、カスタムエラー/例外ハンドラ(この場合のみならず)を使用するのが最善の方法です。しかし、あなたがやっていることに応じて、それは過度のことかもしれません。

+2

:渡された文字列はunserializeableでない場合は、FALSEが返されます。幸運にも、 'serialize(false)'を行う人は幸いです。 – gfaceless

+0

"渡された文字列が直列化不能でない場合、FALSEが返され、** E_NOTICEが発行されます。**" E_もスローされます。 – zedee

2

完全なソリューションには、次のようになります。ドキュメントあたり

<?php 
// As mentioned in the top answer, we need to set up 
// some general error handling 
function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 


// Note, there are two types of way it could fail, 
// the fail2 fail is when try to unserialise just 
// false, it should fail. Also note, what you 
// do when something fails is up to your app. 
// So replace var_dump("fail...") with your 
// own app logic for error handling 
function unserializeSensible($value) { 
    $caught = false; 
    try { 
     $unserialised = unserialize($value); 
    } catch(ErrorException $e) { 
     var_dump("fail"); 
     $caught = true; 
    } 
    // PHP doesn't have a try .. else block like Python 
    if(!$caught) { 
     if($unserialised === false && $value !== serialize(false)) { 
      var_dump("fail2"); 
     } else { 
      var_dump("pass"); 
      return $unserialised; 
     } 
    } 
} 

unserializeSensible('b:0;'); // Should pass 
unserializeSensible('b:1;'); // Should pass 
unserializeSensible('a:2:{s:1:"a";b:0;s:1:"b";s:3:"foo";}'); // Should pass 
unserializeSensible('a:2:{s:1:"a";b:0;s:1:"b";s:3:1111111111111111;}'); // Should fail 
unserializeSensible(123); // Should fail 
unserializeSensible("Gday"); // Should fail 
unserializeSensible(false); // Should fail2 
unserializeSensible(true); // Should fail 
関連する問題