如何在Laravel 5中捕获异常/缺少页面? [英] How do I catch exceptions / missing pages in Laravel 5?
问题描述
在Laravel 5中,App::missing
和App::error
不可用,那么现在如何捕获异常和缺少页面?
我在文档中找不到与此有关的任何信息.
在Laravel 5中,您可以通过在app/Exceptions/Handler.php
中编辑render
方法来捕获异常.
如果要捕获丢失的页面(也称为NotFoundException
),则需要检查异常$e
是否是Symfony\Component\HttpKernel\Exception\NotFoundHttpException
的实例.
public function render($request, Exception $e) {
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
使用上面的代码,我们检查$e
是否为 instanceof
(如果是Symfony\Component\HttpKernel\Exception\NotFoundHttpException
),则我们发送response
" rel ="noreferrer >查看文件error.404
作为 HTTP状态代码404 的内容. /p>
这可以用于任何例外.因此,如果您的应用发送了App\Exceptions\MyOwnException
例外,则应检查该实例.
public function render($request, Exception $e) {
if ($e instanceof \App\Exceptions\MyOwnException)
return ''; // Do something if this exception is thrown here.
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
In Laravel 5, App::missing
and App::error
is not available, so how do your catch exceptions and missing pages now?
I could not find any information regarding this in the documentation.
In Laravel 5 you can catch exceptions by editing the render
method in app/Exceptions/Handler.php
.
If you want to catch a missing page (also known as NotFoundException
) you would want to check if the exception, $e
, is an instance of Symfony\Component\HttpKernel\Exception\NotFoundHttpException
.
public function render($request, Exception $e) {
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
With the code above, we check if $e
is an instanceof
of Symfony\Component\HttpKernel\Exception\NotFoundHttpException
and if it is we send a response
with the view file error.404
as content with the HTTP status code 404.
This can be used to ANY exception. So if your app is sending out an exception of App\Exceptions\MyOwnException
, you check for that instance instead.
public function render($request, Exception $e) {
if ($e instanceof \App\Exceptions\MyOwnException)
return ''; // Do something if this exception is thrown here.
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
这篇关于如何在Laravel 5中捕获异常/缺少页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!