【发布时间】:2018-10-29 10:11:48
【问题描述】:
在我的 symfony4 项目中,我想抛出自定义异常,所以我创建了一个异常类:
ApiException
namespace App\Utils;
class ApiException extends \Exception
{
private $class;
private $function;
public function __construct(string $message, string $class, string $function, int $code = 0, \Exception $previous = null)
{
$this->class = $class;
$this->function = $function;
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return $this->class.'\\'.$this->function.', Line '.$this->line.': '.$this->message;
}
}
抛出异常
throw new ApiException('Please select a date between 1950 and 2050', __CLASS__, __FUNCTION__);
输出
App\\Utils\\Api\\by_year, Line 43: Please select a date between 1950 and 2050
这正是我想要的,但是,我想避免在我的异常抛出中交出__CLASS__ 和__FUNCTION__。
我需要在哪里注入这两个参数才能始终使用它。在 Exception 中调用它会给我 ExceptionClass 的类名和函数名,而不是抛出它的类?
【问题讨论】:
-
你为什么还要搞乱你的构造函数?无论如何,异常回溯会告诉你所有这些!为什么不放弃构造函数而只连接消息字符串呢?
throw new ApiException('Please select a date between 1950 and 2050 in ' . __CLASS__, '::' .__FUNCTION__);
标签: php symfony exception-handling