000*_*000 2 php error-handling class
嘿那里,这是给你们的问题.
我有很多时间为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');
}
}
Run Code Online (Sandbox Code Playgroud)
所以,让我们知道我想要的东西:有没有更好的错误处理解决方案?
Rob*_*itt 12
说到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{}
Run Code Online (Sandbox Code Playgroud)
在你的类中抛出异常并捕获抛出它们的类之外的异常是我通常会做的事情.
用法示例:
$Example = new Example();
try
{
$Examples = $Example->getExamples();
foreach($Examples as $Example)
{
//...
}
}catch(ExampleException $e)
{
Registry::get("Output")->displayError("Unable to perform action",$e);
}
Run Code Online (Sandbox Code Playgroud)
并且您displayError将使用$e->getMessage()有关错误的信息.