本文介绍了Handler.php中的渲染功能无法正常工作Laravel 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to return a JSON response instead of the default 404 error page when ModelNotFoundException occurs. To do this, I wrote the following code into 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 上显示空白页.

However it doesn't work. When the ModelNotFoundException occurs, Laravel just shows a blank page. I find out that even declaring an empty render function in Handler.php makes Laravel display a blank page on ModelNotFoundException.

如何解决此问题,使其可以返回JSON/执行覆盖的渲染函数中的逻辑?

How can I fix this so it can return JSON/execute the logic inside the overriden render function?

推荐答案

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

In Laravel 8x, You need to 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);
    });
}

对于 ModelNotFoundException ,您可以执行以下操作.

For ModelNotFoundException you can do it as below.

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function register()
{
    $this->renderable(function (NotFoundHttpException $e, $request) {
        return response()->json(...);
    });
}

默认情况下,Laravel异常处理程序会将异常转换为HTTP响应.但是,对于给定类型的异常,您可以自由注册自定义渲染闭包.您可以通过异常处理程序的 renderable 方法完成此操作.Laravel将通过检查Closure的类型提示来推断Closure呈现的异常类型:

By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering Closure for exceptions of a given type. You may accomplish this via the renderable method of your exception handler. Laravel will deduce what type of exception the Closure renders by examining the type-hint of the Closure:

有关错误异常的更多信息

More info about the error exception

这篇关于Handler.php中的渲染功能无法正常工作Laravel 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:40