在 app\Exceptions\Handler.php 的 render() 方法中使用$exception变量时



我是Laravel的新手,并且对处理程序.php文件有问题。

我正在尝试创建一个类,该类接受异常并将其转换为 JSON 响应。 可悲的是,在调用构造函数时,会抛出一系列错误: (ErrorErrorErrorErrorErrorErrorErrorT

我的代码: render(( in Handler.php:

public function render($request, Throwable $exception)
{
$errorResource = new ErrorResource($exception);
return $errorResource->getJsonResponse();
}

类 错误资源 in 错误资源.php:

<?php
namespace Transformers;
use Throwable;
class ErrorResource
{
private $exception;
private $defaultCodes = [TypeError::class => 400];
private $defaultMessages = [TypeError::class => 'Untgültige URL Parameter'];
function __construct(Throwable $exception)
{
$this->exception = $exception;
}
public function getJsonResponse($exception)
{
$codeToThrow = 500;
$messageToThrow = "Internal Server Error";
$type = get_class($this->exception);
if (empty($exception->getCode())) {
$codeToThrow = $this->defaultCodes[$type];
} else {
$codeToThrow = $exception->getCode();
}
if (empty($exception->getMessage())) {
$messageToThrow = $this->defaultMessages[$type];
} else {
$messageToThrow = $exception->getMessage();
}
return response()->json(array(
'Type' => $type,
'Message' => $messageToThrow
), $codeToThrow);
}
}

我还尝试将方法getJsonResponse((移动到Handler.php文件并从那里调用它,但没有任何运气。 我真的很困惑为什么不允许我使用 $exception 变量做某些事情(我也尝试创建这个对象的克隆 - 但发生了同样的错误(

希望你能帮我解决这个问题,

问候,

弗朗兹

问题是,PHP 是按值调用的。这就是为什么它隐式尝试克隆一个不可克隆的对象 -> 错误。要解决此问题,可以使用包装器对象,但我决定简单地使用引用调用(https://www.javatpoint.com/php-call-by-reference(

最新更新