处理PHP类中的错误

时间:2016-04-09 04:54:11

标签: php class error-handling

我尝试处理用PHP编写的类中的错误并使用curl,这个类使用3个依赖于彼此的函数(init,sendFirstForm,sendSecondForm),我通过嵌套语句测试结果。

我想管理需要发送电子邮件的两种类型的错误(卷曲连接错误和表单错误),以便我可以修复它们。

此代码不起作用。

class Sender {

    public $error;

    public function __construct() {

        $this->error = '';
    }

    public function send() {

        if($this->init() === TRUE) /* account login and retrieval of the cookie */
        {
            if($this->sendFirstForm() === TRUE) /* sending the first form if connection  */
            {
                if($this->sendSecondForm() === TRUE) /* sending the second form if connection  */
                {
                    echo 'Annonce publiée avec succès.';
                }
            }
        }
    }

    public function init() {

        // CuRL : account login and retrieval of the cookie
        // ...
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
        $result = curl_exec($ch);

        if(curl_errno($ch))
        {
            $this->error = 'CuRL Error : ' . curl_error($ch);
            return $this->error;
        }
        elseif(preg_match("/\bError\b/i", $result)) /* $ _POST data missing and / or incorrect */
        {
            $this->error = 'Error in the login form';
            return $this->error;

            mail('name@domain.com', 'Error Curl', 'Error connecting to the account, here are the data sent : ' . $postfields);
        }
    }

    public function sendFirstForm() {

        // CuRL : sending the first form
        // ...
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
        $result = curl_exec($ch);

        if(curl_errno($ch))
        {
            $this->error = 'CuRL Error : ' . curl_error($ch);
            return $this->error;
        }
        elseif(preg_match("/\bError\b/i", $result)) /* $ _POST data missing and / or incorrect */
        {
            $this->error = 'Error in the first form';
            return $this->error;

            mail('name@domain.com', 'Error Curl', 'Error sending first form, here are the data sent : ' . $postfields);
        }
    }

    public function sendSecondForm() {

        // CuRL : sending the second form
        // ...
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
        $result = curl_exec($ch);

        if(curl_errno($ch))
        {
            $this->error = 'CuRL Error : ' . curl_error($ch);
            return $this->error;
        }
        elseif(preg_match("/\bError\b/i", $result)) /* $ _POST data missing and / or incorrect */
        {
            $this->error = 'Error in the second form';
            return $this->error;

            mail('name@domain.com', 'Error Curl', 'Error sending second form, here are the data sent : ' . $postfields);
        }
    }
}

$send = new Sender();
$send->Send();

if(empty($send->error))
{
    // MySQL treatment
}
else
{
    echo $send->error;
}

0 个答案:

没有答案