【发布时间】:2016-11-10 09:05:10
【问题描述】:
在我开始编写代码之前,让我解释一下我的目标。我的网络应用程序显示待售车辆。如果用户尝试访问不存在的页面,我需要一个自定义 404 页面,该页面将显示添加到数据库中的 12 辆最新车辆。
我有以下...
App\Exceptions\CustomException.php
<?php
namespace App\Exceptions;
use Exception;
class CustomException extends Exception
{
public function __construct()
{
parent::__construct();
}
}
App\Exceptions\CustomHandler.php
<?php
namespace App\Exceptions;
use Exception;
use App\Exceptions\Handler as ExceptionHandler;
use Illuminate\Contracts\Container\Container;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Foundation\Exceptions\Handler;
use Illuminate\Support\Facades\View;
class CustomHandler extends ExceptionHandler
{
protected $vehicle;
public function __construct(Container $container, EloquentVehicle $vehicle)
{
parent::__construct($container);
$this->vehicle = $vehicle;
}
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
$exception = Handler::prepareException($exception);
if($exception instanceof CustomException) {
return $this->showCustomErrorPage();
}
return parent::render($request, $exception);
}
public function showCustomErrorPage()
{
$recentlyAdded = $this->vehicle->fetchLatestVehicles(0, 12);
return View::make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
}
为了测试这个我添加了
抛出新的 CustomException();
到我的控制器,但它没有调出 404Custom 视图。我需要做些什么才能使其正常工作?
更新:只是给任何将他们的类绑定到他们的模型的人的注释。如果您尝试使用以下方法访问类中的函数,您将收到 BindingResolutionException:
app(MyClass::class)->functionNameGoesHere();
要解决这个问题,只需创建一个变量,就像将类绑定到服务提供者中的容器一样。
我的代码如下所示:
protected function showCustomErrorPage()
{
$eloquentVehicle = new EloquentVehicle(new Vehicle(), new Dealer());
$recentlyAdded = $eloquentVehicle->fetchLatestVehicles(0, 12);
return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
阿米特的版本
protected function showCustomErrorPage()
{
$recentlyAdded = app(EloquentVehicle::class)->fetchLatestVehicles(0, 12);
return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
【问题讨论】:
标签: laravel laravel-5 exception