在 Laravel 5.3 中创建自定义异常类和自定义处理程序类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40523610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a custom exception class and custom handler class in Laravel 5.3
提问by VenomRush
Before I get to the code, let me explain my aim. My web app displays vehicles for sale. I have a need for a custom 404 page that will display 12 of the latest vehicles added to the database if the user tries to access a page that doesn't exist.
在进入代码之前,让我解释一下我的目标。我的网络应用程序显示待售车辆。如果用户尝试访问不存在的页面,我需要一个自定义 404 页面,该页面将显示添加到数据库中的 12 辆最新车辆。
I have the following...
我有以下...
App\Exceptions\CustomException.php
App\Exceptions\CustomException.php
<?php
namespace App\Exceptions;
use Exception;
class CustomException extends Exception
{
public function __construct()
{
parent::__construct();
}
}
App\Exceptions\CustomHandler.php
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);
}
}
To test this I added
为了测试这个我添加了
throw new CustomException();
抛出新的 CustomException();
to my controller but it doesn't bring up the 404Custom view. What do I need to do to get this working?
到我的控制器,但它不会显示 404Custom 视图。我需要做什么才能让它发挥作用?
UPDATE: Just a note for anyone who's bound their class to their model. You'll get a BindingResolutionException if you try to access a function in your class using:
更新:对于将他们的班级绑定到他们的模型的任何人来说,这只是一个注释。如果您尝试使用以下方法访问类中的函数,则会收到 BindingResolutionException:
app(MyClass::class)->functionNameGoesHere();
app(MyClass::class)->functionNameGoesHere();
To get around this simply create a variable in the same way you would bind your class to the Container in your service provider.
要解决这个问题,只需按照将类绑定到服务提供者中的 Container 的相同方式创建一个变量。
My code looks like this:
我的代码如下所示:
protected function showCustomErrorPage()
{
$eloquentVehicle = new EloquentVehicle(new Vehicle(), new Dealer());
$recentlyAdded = $eloquentVehicle->fetchLatestVehicles(0, 12);
return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
Amit's version
阿米特的版本
protected function showCustomErrorPage()
{
$recentlyAdded = app(EloquentVehicle::class)->fetchLatestVehicles(0, 12);
return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
回答by Amit Gupta
Laravel calls the render
function of App\Exceptions\Handler
class. So overriding it will not work.
Laravel 调用类的render
函数App\Exceptions\Handler
。所以覆盖它是行不通的。
You have to add it in App\Exceptions\Handler
class only.
你App\Exceptions\Handler
只需要在课堂上添加它。
For example:
例如:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* 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)
{
if($exception instanceof CustomException) {
return $this->showCustomErrorPage();
}
return parent::render($request, $exception);
}
protected function showCustomErrorPage()
{
$recentlyAdded = app(EloquentVehicle::class)->fetchLatestVehicles(0, 12);
return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
}
回答by Ali Ali
In new versions of Laravel, you can create a custom handler using this command:
在新版本的 Laravel 中,您可以使用以下命令创建自定义处理程序:
php artisan make:exception CustomException
Then you should call these methods "report(), render()" inside your custom handler and they will override the existing ones in the App\Exceptions\Handler
.
然后,您应该在自定义处理程序中调用这些方法“ report()、render()”,它们将覆盖App\Exceptions\Handler
.
report() used if you want to log the errors.
如果您想记录错误,请使用 report()。
render() used if you want to redirect back with error or return HTTP response (like your own Blade file) or if you're building an API.
如果您想重定向返回错误或返回 HTTP 响应(如您自己的 Blade 文件),或者您正在构建 API,则使用 render()。
For more information, you can check Laravel documentation.
有关更多信息,您可以查看Laravel 文档。