这是处理异常消息的好方法吗?

时间:2012-06-19 17:21:40

标签: php exception-handling

我想要一些系统,我不必一直看着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;
    }
}

我的问题是,是否有更明智的方法来做这类事情?

1 个答案:

答案 0 :(得分:2)

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

您的异常类正在破坏Single Responsibility Principle (SRP)­Wikipedia,因为您对不同类型的错误使用相同的异常类。我要做的是:

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

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

然后你可以使用excetion而不传递任何消息。该消息是类的私有部分。

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