我想返回 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);
}
然而它不起作用。当。。。的时候模型未发现异常发生时,Laravel 仅显示一个空白页面。我发现即使在中声明一个空的渲染函数Handler.php
使 Laravel 显示空白页模型未发现异常.
我该如何解决这个问题,以便它可以返回 JSON/执行覆盖渲染函数内的逻辑?
在 Laravel 8x 中,你需要Rendering Exceptions
in register()
method
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);
});
}
For ModelNotFoundException
你可以这样做。
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(...);
});
}
默认情况下,Laravel 异常处理程序会将异常转换为 HTTP 响应。但是,您可以自由地为给定类型的异常注册自定义渲染闭包。您可以通过以下方式完成此操作renderable
异常处理程序的方法。 Laravel 将通过检查 Closure 的类型提示来推断 Closure 呈现的异常类型:
有关的更多信息错误异常 https://laravel.com/docs/8.x/errors#rendering-exceptions
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)