PHP - 带有行号的自定义异常消息


PHP - Custom Exception Message With Line Number

假设我有一个类,它在实例化时接受SomeClass数组,例如:

class ConfigurableClass
{
    public function __construct( array $config = array() )
    {
        foreach( $config as $param )
        {
            if( !$param instanceof SomeClass )
            {
                $type = gettype($param);
                $line = ? // How can I retrieve this?
                throw new Exception("ConfigurableClass config parameters must be of type SomeClass, $type given in line $line");
            }
        } 
    }
}

假设这个类在不同的文件中实例化,其中包含一个具有错误类型的元素的数组,例如:

$instance = new ConfigurableClass(array(
   new SomeClass(),
   new SomeClass(),
   new SomeClass(),
   'Ooops!',       // String type, line 5
   new SomeClass()
));

如何抛出一条错误消息,指定插入错误对象类型的行号?在这种情况下,相应的消息应为:

"ConfigurableClass config parameters must be of type SomeClass, string given in line 4"

请记住,这只是一个例子。真正的类可以接受一个非常大和复杂的数组。在这种情况下,知道行号可能非常有用。

无法确定该行(在您的情况下为 5),因为它是在调用者指令的末尾给出的,即分号所在的位置(在您的例子中为 7)。

但是,您可以通过显示该行号和错误的参数号来获得良好的近似值。

<?php
class ConfigurableClass
{
    public function __construct( array $config = array() )
    {
        $counter = 0;
        foreach( $config as $param )
        {
            if( !$param instanceof SomeClass )
            {
                $type = gettype($param);
                $line = debug_backtrace()[0]['line'];
                throw new Exception("ConfigurableClass config parameter[$counter] must be of type SomeClass, $type given in line $line");
            }
            $counter++;
        } 
    }
}

消息将如下所示:

致命错误:未捕获的异常"异常",消息"可配置类配置参数[3]"必须是 SomeClass,字符串在第 12 行的 C:''your''folder''origin_file.php 第 12 行中给出,在第 15 行 C:''your''folder''ConfigurableClass.php

如果要在消息中避免引用 ConfigurableClass 文件和行,则必须创建自己的派生异常类并覆盖 __toString() 方法。

最简单的也许

class MyException extends Exception {
  public $file;
  public $line;
}
$e = new MyException('error message');
$e->file = 'foo.php';
$e->line = 20220501;
throw $e;