Error Handling in a PHP Class

2020-06-06 04:31发布

问题:

Hey there, here is a question for you guys.

I have so much times to choose a error handling for classes in PHP.

For Example in Ajax PHP Handling Classes i do it this way:

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');
    }
}

So lets know you what i want to aks for: Is there a better solution for error handling?

回答1:

When it comes to OOP Your best bet is to use Exceptions to handle your errors, for example:

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

class ExampleException extends Exception{}

throwing exceptions within your class and catching exceptions outside of the classes that throw them is the way I usually go about things.

Usage Example:

$Example = new Example();
try
{
    $Examples = $Example->getExamples();

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

and your displayError would use $e->getMessage() as the information regarding the error.



回答2:

Generally when programming in OOP, you will make heavy use of Exceptions as your "error" handler.

See http://php.net/exceptions