Gateway如何捕捉Warning: Undefined array key 1

黑老怪

问题描述

Try catch 用了 但是没有办法捕捉到 我用的\Throwable

程序代码或配置

<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */

//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public static function onWorkerStart()
    {
        $aTest = [];
        try {
            $a = $aTest[1];
        } catch (\Throwable $aErr) {
            echo 'Err----';
//            var_dump($aErr->getMessage());
        }
    }

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
    }
}

重现问题的步骤

直接在官网下载的最新版本,然后在Events里面加了一个onWorkerStart

操作系统环境及workerman/webman等具体版本

PHP 8.1

552 2 1
2个回答

mosquito

你写法问题,要么 $aTest[1] ?? null; 要么把错误级别改下error_reporting(E_ALL & ~E_NOTICE);

  • 暂无评论
yongdao35

Try catch 捕获不到 Warning Notice这些。Try catch 只能捕获异常Exception或者Error。

onWorkerStart 里执行一句

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    throw new \Exception($errstr, 0, $errno, $errfile, $errline);
});

这样当发生Warning Notice这些会触发异常,就能捕获了

  • 暂无评论
🔝