【问题标题】:Catch FTP Laravel exceptions捕获 FTP Laravel 异常
【发布时间】:2021-04-06 16:37:30
【问题描述】:

我第一次尝试使用 Laravel 异常处理。 我需要的是捕捉我在尝试连接到 FTP 服务器时遇到的不同异常(例如,无法连接、错误的用户/密码、找不到新文件、无法打开文件)。 我被卡住了,因为我看到 Laravel 已经有一个抛出异常的类(位于 vendor/league/flysystem/src/Adapted/Ftp.php)和 Handler.php 但我不明白它们是如何一起工作的以及如何我可以根据异常呈现不同的消息。

非常感谢您的帮助。

【问题讨论】:

  • 使用 try catch 捕获特定异常,然后使用 League\Flysystem\FilesystemException 捕获剩余的异常

标签: laravel exception ftp


【解决方案1】:

Handler.php 将封装任何调用并处理任何扩展 PHP 原生类 \Exception 的异常。所以,无论异常在哪里触发,handler都会尝试去处理。

您可以通过两种方式自定义响应。

  • 在处理程序之前捕获异常: 基本上,用 try catch 包围可以触发异常的代码行
try {
    connectFTP();
} catch (\Exception $e) { //better use FilesystemException class in your case
    //handle it
} 
  • 适配Handler.php:这里有两种方式:
  1. 补丁:只需在渲染方法中拦截有问题的异常

Handler.php laravel 8.x(添加方法)

public function render($request, Exception $e)
{
    if ($e instance of \FtpException) {
        //handle it here
    }
    parent::render($request, $e);
}
  1. 使用你自己的异常类:More info here
class FtpConnectionException extends Exception
{
    /**
     * Report the exception.
     *
     * @return bool|null
     */
    public function report()
    {
        //
    }

    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response(...);
    }
}

在 Vendor 文件夹中触发异常时,如何使用自己的异常类?使用 try catch 方法

try {
    connectFTP();
} catch (\Exception $e) { //better use FilesystemException class in your case
    throw new FtpConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
} 

注意:一些异常不会到达 Handler.php,例如 CSRF 419 异常和 404 页面未找到异常。

【讨论】:

  • 我还读到您应该对 Handler 说自定义异常必须由我的自定义异常类处理。有可能的?无论如何,仍在尝试您的建议,但没有得到预期的结果。此外,我看到 Laravel 8 使用 Throwable 而不是 Exception 类。有什么区别吗?很抱歉所有这些问题。
  • @AlessandroBoscato 再次检查 2。使用您自己的异常类。无论如何,在 PHP 中 \Excetion::class 扩展了 \Throwable::class。两个类扩展了 \Throwable::class、Error::class 和 Exception::class。 Error::class 用于更严重的事情,例如内存不足、算术错误、编译错误...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2014-12-25
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
相关资源
最近更新 更多