gpt4 book ai didi

php - Handler.php中的渲染功能无法正常工作Laravel 8

转载 作者:行者123 更新时间:2023-12-03 11:22:05 27 4
gpt4 key购买 nike

发生 ModelNotFoundException 时,我想返回一个JSON响应,而不是默认的404错误页面。为此,我将以下代码写入app\Exceptions\Handler.php:

public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}

return parent::render($request, $exception);
}
但是,它不起作用。当出现 ModelNotFoundException 时,Laravel仅显示空白页面。我发现,即使在 Handler.php中声明一个空的渲染函数,Laravel也会在 ModelNotFoundException 上显示空白页面。
如何解决此问题,使其可以返回JSON/执行覆盖的渲染函数中的逻辑?

最佳答案

在Laravel 8x中,您需要使用Rendering Exceptions方法中的register()

use App\Exceptions\CustomException;

/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (CustomException $e, $request) {
return response()->view('errors.custom', [], 500);
});
}
对于 ModelNotFoundException,您可以按照以下步骤进行操作。
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(...);
});
}
默认情况下,Laravel异常处理程序会将异常转换为HTTP响应。但是,对于给定类型的异常,您可以自由注册自定义渲染闭包。您可以通过异常处理程序的 renderable方法完成此操作。 Laravel将通过检查闭包的类型提示来推断闭包呈现的异常类型:
有关 error exception的更多信息

关于php - Handler.php中的渲染功能无法正常工作Laravel 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64245534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com