Php 拉威尔罐头';t捕获异常并重定向错误消息

Php 拉威尔罐头';t捕获异常并重定向错误消息,php,laravel,laravel-blade,Php,Laravel,Laravel Blade,我试图捕获PostTooLargeException错误,并用错误消息重定向它。这是我写的处理程序 if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) { return redirect()->back()->withErrors(['msg', 'Post is too large']); } “我的创建”页面具有检查错误的功能,当im在控制器上和通过路由进行测试时,它可以

我试图捕获PostTooLargeException错误,并用错误消息重定向它。这是我写的处理程序

if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) {
   return redirect()->back()->withErrors(['msg', 'Post is too large']);
}
“我的创建”页面具有检查错误的功能,当im在控制器上和通过路由进行测试时,它可以正常工作

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
@if($errors->any())
    @foreach($errors->all()作为$error)
  • {{$error}}
  • @endforeach
@恩迪夫
重定向工作,但我不能得到错误消息,它不会显示任何东西。我错过什么了吗

更新
下面的帖子帮助了我,但还有一个问题,那就是php.ini post_max_size,当我增加它时,一切都开始工作了。当然要结合下面的代码。

我认为您试图使用“msg”作为“Post太大”的键,如果是这种情况,它应该是一个关联数组

->withErrors(['msg' => 'Post is too large'])

但是,即使有代码,它也应该在ul元素中显示“msg”和“Post太大”的错误。因此,在该容器中有两个列表项。在重定向过程中,您不会发现您共享的内容在技术上有任何错误。

您可以在
app/Exceptions/handler.php的
render
方法中添加重定向处理程序,如下所示:

/**
 * 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 \Illuminate\Http\Exceptions\PostTooLargeException) {

       return \Illuminate\Support\Facades\Redirect::back()->withErrors(['msg' => 'The Message']);
    }

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

然后,它会将flash会话中的错误发送给您,并在前端显示。

同样的代码适用于controller,它会显示一条小警报消息,一条说“msg”,另一条说“post太大”。正确,这是我从您的代码片段中预期会发生的情况。你提到“这就是我写的处理程序”。所以它在某种处理程序中不起作用?它是异常处理程序,位于app\exceptions\handler.php中。由于某些原因,它不在那里工作,而是在控制器和路由内部工作。如果在异常处理程序的render函数中有重定向,那么重定向功能应该与控制器中的重定向功能一样工作。只要您来自的页面是创建页面,它就应该重定向回那里并显示这些错误。我用你的代码进行了测试,效果很好,因此没有更多详细信息,我不确定你那边发生了什么。我假设这个问题以某种方式连接到了我的本地服务器。如果你在FrontEnd上显示错误,这应该会将控件发送回发送post数据的表单。我只是在我的项目上尝试了一次试运行,并且作品你能告诉我发生了什么吗?让我们继续聊天