如何在Laravel中捕获PostTooLargeException? [英] How to catch PostTooLargeException in Laravel?

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

问题描述

要重现该错误,只需将文件上传到Laravel中任何超过您 php.ini 配置中的 post_max_size 的POST路由.

To reproduce the error, simply upload a file(s) to any POST routes in Laravel that exceeds the post_max_size in your php.ini configuration.

我的目标是简单地捕获错误,以便通知用户他上传的文件太大.说:

My goal is to simply catch the error so I can inform the user that the file(s) he uploaded is too large. Say:

public function postUploadAvatar(Request $request)
  try {
    // Do something with $request->get('avatar')
    // Maybe validate file, store, whatever.
  } catch (PostTooLargeException $e) {
    return 'File too large!';
  }
}

以上代码在标准Laravel 5(PSR-7)中.问题在于一旦注入的请求发生错误,该函数就无法执行.从而无法在函数内部捕获它.那怎么抓呢?

The above code is in standard Laravel 5 (PSR-7). The problem with it is that the function can't execute once an error occurs on the injected request. Thereby can't catch it inside the function. So how to catch it then?

推荐答案

Laravel使用其 ValidatePostSize 中间件检查请求的 post_max_size ,然后抛出PostTooLargeException 如果请求的 CONTENT_LENGTH 过大.这意味着该异常甚至在到达控制器之前就被抛出.

Laravel uses its ValidatePostSize middleware to check the post_max_size of the request and then throws the PostTooLargeException if the CONTENT_LENGTH of the request is too big. This means that the exception if thrown way before it even gets to your controller.

您可以做的是在 App \ Exceptions \ Handler 中使用 render()方法,例如

What you can do is use the render() method in your App\Exceptions\Handler e.g.

public function render($request, Exception $exception)
{
    if ($exception instanceof PostTooLargeException) {

        return response('File too large!', 422);
    }

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

请注意,您必须从此方法返回响应,不能像从控制器方法中那样仅返回字符串.

Please note that you have to return a response from this method, you can't just return a string like you can from a controller method.

上面的响应是复制返回文件太大!"; 在问题示例中,您显然可以将其更改为其他内容.

The above response is to replicate the return 'File too large!'; you have in the example in your question, you can obviously change this to be something else.

希望这会有所帮助!

这篇关于如何在Laravel中捕获PostTooLargeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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