laravel-response icon indicating copy to clipboard operation
laravel-response copied to clipboard

无法捕获 ModelNotFoundException 异常类

Open Mr-wangwei opened this issue 9 months ago • 3 comments

Image config 中 无法捕获 ModelNotFoundException异常类,laravel 11 会将 ModelNotFoundException转成 NotFoundHttpException类 Image

Mr-wangwei avatar Feb 28 '25 10:02 Mr-wangwei

看有好的实现思路提供吗?

jiannei avatar Mar 04 '25 06:03 jiannei

可以在 vendor/jiannei/laravel-response/src/Http/Exceptions/Handler.php 文件中重写 prepareException 这个方法。

<?php

/*
 * This file is part of the jiannei/laravel-response.
 *
 * (c) Jiannei <[email protected]>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Jiannei\Response\Laravel\Http\Exceptions;

......
class Handler extends \Illuminate\Foundation\Exceptions\Handler
{
    use ExceptionTrait;

    protected function prepareException(\Throwable $e)
    {
        return match (true) {
            $e instanceof BackedEnumCaseNotFoundException => new NotFoundHttpException($e->getMessage(), $e),
            $e instanceof ModelNotFoundException => $e,
            $e instanceof AuthorizationException && $e->hasStatus() => new HttpException(
                $e->status(), $e->response()?->message() ?: (Response::$statusTexts[$e->status()] ?? 'Whoops, looks like something went wrong.'), $e
            ),
            $e instanceof AuthorizationException && ! $e->hasStatus() => new AccessDeniedHttpException(__($e->getMessage()), $e),
            $e instanceof TokenMismatchException => new HttpException(419, $e->getMessage(), $e),
            $e instanceof RequestExceptionInterface => new BadRequestHttpException('Bad request.', $e),
            $e instanceof RecordNotFoundException => new NotFoundHttpException('Not found.', $e),
            $e instanceof RecordsNotFoundException => new NotFoundHttpException('Not found.', $e),
            default => $e,
        };
    }
}


`

Mr-wangwei avatar Mar 04 '25 06:03 Mr-wangwei

可以来个 pr ~

jiannei avatar Mar 04 '25 06:03 jiannei