首页 > 解决方案 > 在 Laravel 5 上全局捕获 ModelNotFoundException

问题描述

我试图从 app\Exceptions\Handler 类全局捕获ModelNotFoundException,因此不必在每个控制器上检查它。

但它不起作用,尽管它在控制器内部工作正常:

try {

        $asset = Asset::findOrFail($asset_id);

    } catch (Exception $e) {

        if ($e instanceof ModelNotFoundException)
        {
            $model = explode('\\', $e->getModel());
            return $this->respondWithRecordNotFound(end($model) . ' record not found');
        }

        return $this->respondWithGeneralError($e->getMessage());
    }

应用程序\异常\处理程序:

public function render($request, Exception $exception)
{

    if ($exception instanceof ModelNotFoundException) 
    {
        $model = explode('\\', $exception->getModel());
        return $this->respondWithRecordNotFound(end($model) . ' record not found');
    }

    return parent::render($request, $exception);
}

标签: laravellaravel-5laravel-5.7

解决方案


我不确定你respondWithRecordNotFound在做什么。我想问题可能就在那里。

无论如何,我只是尝试了一下,这对我有用。在App\Exceptions\Handler.php@render

if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
    return response()->view(
        'errors.404', 
        ["message" => $e->getModel() . ' record not found'], 
        404
    );
}

推荐阅读