Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Handling in a PHP Class

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?

like image 999
000 Avatar asked Dec 08 '25 01:12

000


1 Answers

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.

like image 78
RobertPitt Avatar answered Dec 10 '25 13:12

RobertPitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!