5中处理PostTooLargeException

5中处理PostTooLargeException

本文介绍了在Laravel 5.5中处理PostTooLargeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Laravel 5.5应用程序中处理PostTooLargeException.

I am trying to handle PostTooLargeException in my Laravel 5.5 application.

当我尝试通过表单上传太大的文件时,我收到PostTooLargeException并成功捕获到app\Exceptions\Handler.php,但是在此步骤中,我想将用户重定向到包含表单的页面并显示错误消息.

When I trying to upload too big file through my form I receive PostTooLargeException which I successfully catch in app\Exceptions\Handler.php, but on that step I would like to redirect user back to the page with form and show an error message.

我写了以下代码:

class Handler extends ExceptionHandler
{
...
    public function render($request, Exception $exception)
    {
    ...
        if($exception instanceof PostTooLargeException){
                    return redirect()->back()->withErrors("Size of attached file should be less ".ini_get("upload_max_filesize")."B", 'addNote');
            }
    ...
    }
}

结果,我被重定向到正确的页面,但没有任何消息,并且ViewErrorBag为空.重定向是否有问题?

As a result I was redirected to the proper page but without any message and ViewErrorBag was empty.Did I something wrong with that redirection?

谢谢您的帮助!

推荐答案

ViewErrorBag为空,因为会话不在Handler中启动.以前, @Talinon 描述了解决方案,网址为 Laracast

The ViewErrorBag is empty because session is not start in the Handler. Solution was previously described by @Talinon at Laracast

为了使会话在Handler类中可用,我将\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class$middleware移到了App/Http/Kernel.php

To make session available in the Handler class, I moved \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class from $middleware to $middlewareGroups array at the App/Http/Kernel.php

我更新的$middlewareGroups数组如下:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, // <<< this line was added
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,

        ],
        ...
];

这篇关于在Laravel 5.5中处理PostTooLargeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:14