如何捕获反序列化异常?

Eug*_*ene 18 php serialization try-catch

当unserialize生成错误时,如何在PHP上捕获异常?

Mih*_*rga 13

不,你不能抓住它,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");
Run Code Online (Sandbox Code Playgroud)


Joh*_*hni 12

一个简单的方法是:

$ret = @unserialize($foo);
if($ret === null){
   //Error case
}
Run Code Online (Sandbox Code Playgroud)

但它不是最现代化的解决方案.

如前所述,最好的方法是拥有自定义错误/异常处理程序(不仅适用于此情况).但取决于你在做什么,这可能是矫枉过正.

  • per documentation:如果传递的字符串不可反序列化,则返回FALSE.幸运的是很少有人会`序列化(假)` (5认同)
  • 这不是一个好的答案。最初的序列化值可能为空。`serialize(NULL)` 是 `"N;"` 反序列化为 `NULL`。在大多数情况下没有人序列化 null,但这可能发生在一些复杂的自动化系统或计算中——例如,停止问题计算的输出(其中 NULL 与 FALSE 不同)。 (2认同)
  • 您需要将检查修改为至少 `if($foo!="N;" && $ret === null){ //Error case }` 因此您知道源变量不为 null,因此 null 作为错误。 (2认同)

Hem*_*ulo 5

将所有 PHP 错误(警告通知等)转换为异常。例子在这里


Chr*_*ris 5

完整的解决方案如下所示:

<?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
Run Code Online (Sandbox Code Playgroud)