myd
V2EX  ›  PHP

PHP 如何捕获 Catchable fatal error?

  •  1
     
  •   myd · Mar 12, 2020 · 3805 views
    This topic created in 2429 days ago, the information mentioned may be changed or developed.

    执行 N 个任务,执行任务可能报错,如果报错则执行下一个。

    <?php
    error_reporting(E_ALL);
    ini_set("display_errors", "On");
    
    
    for ($i = 0; $i < 5; $i++) {
        try {
            task($i);
        } catch (Exception|Error $exception) {
            echo "执行失败,下一个";
            continue;
        }
    }
    
    
    function task($task_id)
    {
        echo "执行任务 $task_id";
        if ($task_id == 2) {
            echo new stdClass();
        }
        echo " 成功\n";
    }
    

    期望结果:

    执行任务 0 成功
    执行任务 1 成功
    执行任务 2 执行失败,下一个
    执行任务 3 成功
    执行任务 4 成功
    

    实际上执行结果:

    执行任务 0 成功
    执行任务 1 成功
    执行任务 2
    Catchable fatal error: Object of class stdClass could not be converted to string
    

    执行任务 2 时,提示 Catchable fatal error。如何捕获这个错误?

    3 replies  •  2020-03-13 09:08:32 +08:00
    myd
    myd
    OP
    Mar 12, 2020
    2
    @Littlesqx 非常感谢
    dilu
    dilu
    Mar 13, 2020
    3
    1L 正解 还可以全局捕获异常等等
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2760 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:38 · PVG 08:38 · LAX 16:38 · JFK 19:38
    ♥ Do have faith in what you're doing.