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

问题描述

在 Laravel 5 中,App::missingApp::error 不可用,那么您现在如何捕获异常和丢失页面?

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.

推荐答案

在 Laravel 5 中,您可以通过编辑 app/Exceptions/Handler.phprender 方法来捕获异常>.

In Laravel 5 you can catch exceptions by editing the render method in app/Exceptions/Handler.php.

如果您想捕获丢失的页面(也称为 NotFoundException),您需要检查异常 $e 是否是 的一个实例SymfonyComponentHttpKernelExceptionNotFoundHttpException.

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 SymfonyComponentHttpKernelExceptionNotFoundHttpException.

public function render($request, Exception $e) {
    if ($e instanceof SymfonyComponentHttpKernelExceptionNotFoundHttpException)
        return response(view('error.404'), 404);

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

使用上面的代码,我们检查 $e 是否是 instanceofSymfonyComponentHttpKernelExceptionNotFoundHttpException 并且如果它是我们发送一个 response查看文件 error.404 作为内容HTTP 状态代码 404.

With the code above, we check if $e is an instanceof of SymfonyComponentHttpKernelExceptionNotFoundHttpException and if it is we send a response with the view file error.404 as content with the HTTP status code 404.

这可用于任何异常.因此,如果您的应用发出 AppExceptionsMyOwnException 异常,请改为检查该实例.>

This can be used to ANY exception. So if your app is sending out an exception of AppExceptionsMyOwnException, you check for that instance instead.

public function render($request, Exception $e) {
    if ($e instanceof AppExceptionsMyOwnException)
        return ''; // Do something if this exception is thrown here.

    if ($e instanceof SymfonyComponentHttpKernelExceptionNotFoundHttpException)
        return response(view('error.404'), 404);

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

这篇关于如何在 Laravel 5 中捕获异常/丢失的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 11:43