Handler.php 中的渲染函数不起作用 Laravel 8

Ros*_*fri 9 php laravel laravel-8

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);
}
Run Code Online (Sandbox Code Playgroud)

但是它不起作用。当ModelNotFoundException发生时,Laravel 只显示一个空白页面。我发现,即使是在宣告一个空的渲染功能Handler.php品牌Laravel上显示空白页ModelNotFoundException

我该如何解决这个问题,以便它可以返回 JSON/执行覆盖渲染函数中的逻辑?

Dil*_*ara 14

在 Laravel 8x 中,你需要Rendering Exceptionsregister()方法中

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

因为ModelNotFoundException您可以按如下方式进行。

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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

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

有关错误异常的更多信息

  • 为什么必须在“ModelNotFoundException”的处理程序中使用“NotFoundHttpException”异常?我有一个问题,404 错误也会引发 `NotFoundHttpException`,但我想为这些异常引发不同的错误 (3认同)

The*_*rKa 8

这段代码对我不起作用(在 Laravel 8.74.0 中):

$this->renderable(function (ModelNotFoundException$e, $request) {
    return response()->json(...);
});
Run Code Online (Sandbox Code Playgroud)

不知道为什么,但ModelNotFoundException直接转发到Laravel 使用的(这是Symfony 组件NotFoundHttpException的一部分),最终会触发 404 HTTP 响应。我的解决方法是检查异常的方法:getPrevious()

$this->renderable(function (NotFoundHttpException $e, $request) {
  if ($request->is('api/*')) {
    if ($e->getPrevious() instanceof ModelNotFoundException) {
        return response()->json([
            'status' => 204,
            'message' => 'Data not found'
        ], 200);
    }
    return response()->json([
        'status' => 404,
        'message' => 'Target not found'
    ], 404);
  }
});
Run Code Online (Sandbox Code Playgroud)

然后我们就会知道这个异常来自ModelNotFoundException并返回不同的响应NotFoundHttpException

编辑

就是为什么ModelNotFoundException抛出NotFoundHttpException