我想要一些系統,我不必一直看着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;
}
}
我的問題是,是否有一個明顯更好的方式做這樣的事情?
我會說這是更適合[代碼評論](http://codereview.stackexchange.com/faq) – vascowhite
他們是獲得設計模式幫助的地方嗎? –
是的,我鏈接到FAQ。 – vascowhite