如何在Laravel 5中捕获异常/缺少页面? [英] How do I catch exceptions / missing pages in Laravel 5?

查看:141
本文介绍了如何在Laravel 5中捕获异常/缺少页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 5中,App::missingApp::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆