【问题标题】:Error Handling in a PHP ClassPHP 类中的错误处理
【发布时间】:2011-02-13 19:53:41
【问题描述】:

你好, 这里有一个问题要问你们。

我有很多时间为 PHP 中的类选择错误处理。

例如,在 Ajax PHP 处理类中,我这样做:

public function setError($msg) {
    $this->errors[] = $msg;
}

public function isFailed() {
    return (count($errors) > 0 ? true : false); // if errors > 0 the request is failed
}

public function getJsonResp() {
    if($this->isFailed()) {
        $resp = array('result' => false, 'message' => $this->errors[0]);
    } else {
        $resp = array('result' => true);
        array_merge($resp, $this->success_data); // the success data is set later
    }
    return json_encode($resp);
}

// an example function for a execution of a method would be this

public function switchMethod($method) {
    switch($method) {
        case 'create':
            if(!isset($param1, $param2)) {
                $this->setError('param1 or param2 not found');
            } else {
                $this->createSomething();
            }
            break;
        default:
            $this->setError('Method not found');
    }
}

所以让你知道我想要什么: 有没有更好的错误处理解决方案?

【问题讨论】:

    标签: php class error-handling


    【解决方案1】:

    当涉及到 OOP 时,最好的办法是使用 Exceptions 来处理您的错误,例如:

    class Example extends BaseExample implements IExample
    {
        public function getExamples()
        {
            if($this->ExamplesReady === false)
            {
                throw new ExampleException("Examples are not ready.");
            }
        }
    }
    
    class ExampleException extends Exception{}
    

    在你的类中抛出异常并在抛出它们的类之外捕获异常是我通常做事的方式。

    用法示例:

    $Example = new Example();
    try
    {
        $Examples = $Example->getExamples();
    
        foreach($Examples as $Example)
        {
            //...
        }
    }catch(ExampleException $e)
    {
        Registry::get("Output")->displayError("Unable to perform action",$e);
    }
    

    您的displayError 将使用$e->getMessage() 作为有关错误的信息。

    【讨论】:

    • 我必须在每个函数中都使用 try & catch 吗?
    • 不,仅在可能发生错误的情况下,在大多数函数中,您可以依靠简单的 if 语句来防止错误,例如除以零异常。
    【解决方案2】:

    通常在 OOP 中编程时,您会大量使用异常作为“错误”处理程序。

    http://php.net/exceptions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      相关资源
      最近更新 更多