1

我想要一些系统,我不必一直查看 Exception 类并一次复制状态代码或文本。我也不想在捕获异常后继续编写简单的英文错误消息。这似乎可以实现两者,而且还可以轻松完成 IDE 自动完成!

这是一些演示代码:

<?php

class Thrive_URL_Exception extends Thrive_PrettyException
{
    const MISSING_CURL = "The cURL PHP extension must be enabled.";
    const MISSING_URL = "A URL has not been supplied or set.";
    const INVALID_URL = "The URL '%s' is not valid.";
    const BLANK_URL = "The URL '%s' contained no data. It is probably invalid.";
    const CONNECTION_TIMED_OUT = "The connection timed out.";
    const FILE_NOT_FOUND = "404: '%s' could not be found.";
    const NOT_ACCESSIBLE = "%d: '%s' is not currently accessible.";
    const PERMISSION_DENIED = "Permission denied.";
}

class Thrive_URL_Downloader
{
    public function fetch($url)
    {
        // Make sure the URL is valid.
        if (!self::isURLValid($url))
        {
            throw new Thrive_URL_Exception(Thrive_URL_Exception::INVALID_URL, array($url));
        }

        $ch = curl_init();
        curl_setopt_array($ch, array(CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_HEADERFUNCTION => array($this, 'captureHeader'),
                CURLOPT_TIMEOUT => 30,
            )
        );

        $data = curl_exec($ch);
        curl_close($ch);

        if ($data === false || is_null($data) || $data == '')
        {
            throw new Thrive_URL_Exception(Thrive_URL_Exception::BLANK_URL, array($url));
        }

        // TODO: Need to handle HTTP error messages, such as 404 and 502.
        $info = $this->getUrlInfo($ch);

        if ($info->httpCode == 401)
        {
            throw new Thrive_URL_Exception(Thrive_URL_Exception::PERMISSION_DENIED);
        }

        if ($info->httpCode == 404)
        {
            throw new Thrive_URL_Exception(Thrive_URL_Exception::FILE_NOT_FOUND, array($url));
        }

        if (in_array($info->httpCode, array(400, 401, 402, 403, 500, 501, 502, 503)))
        {
            throw new Thrive_URL_Exception(Thrive_URL_Exception::NOT_ACCESSIBLE, array($info->httpCode, $url));
        }

        $urlContent = new Thrive_Model_URLContent;
        $urlContent->url = $url;
        $urlContent->headers = $this->headers;
        $urlContent->info = $info;
        $urlContent->content = $data;

        return $urlContent;
    }
}

我的问题是是否有明显更好的方法来做这种事情?

4

1 回答 1

2

恕我直言,这不是最好的解决方案。

您的异常类违反了单一职责原则(SRP) Wikipedia,因为您对不同类型的错误使用相同的异常类。我要做的是:

为不同类型的错误创建单个异常类:

 InvalidUrlException
 PermissionDeniedException
 FileNotFoundException (probalny this exception exists in core php)

然后您可以使用 excetion 而不传递任何消息。该消息是课程的私人部分。

对于更大的应用程序,这个解决方案是更好的恕我直言。

于 2012-06-19T17:30:29.313 回答