php error reporting
Is there a common standard for reporting errors in your class functions?
I've seen some c functions that you pass the error string to, so that if there is an error you can see what it is in that string, You need pointers for that though.
开发者_高级运维I'm reluctant to use the return, because sometimes you do need the return for other variables.
One thing I was trying is using a standardized return object that has an error key inside, as well as the data. This seems to work ok, but when using it with other classes, seems a bit clumsy.
so here's my latest idea, the class has an internal variable $error and every time a function is called, $error gets cleared, and updated with the error string or array (could even hold more than one error) and when the function completes we can check if the error is empty.
here's the problem with that, if I'm using functions within functions, I end up clearing the error. I could hold the string inside a different var, and only push it to error once the before return.
any other ideas to do this gracefully and reliably?
This is an oft-debated topic, and there is no one true answer.
But here are four most common patterns that I'm familiar with
- Exceptions
- Multiple return values / Error Codes
- Error Parameter
- Error State
And a quick example of each
Exceptions
function doSomething()
{
if ( /* expression */ )
{
throw new Exception( 'something went wrong' );
}
}
// Let the registered exception handler do the work
doSomething();
// Or handle this call specifically
try {
doSomething();
}
catch ( Exception $e )
{
echo $e->getMessage();
}
Error Codes
function doSomething()
{
if ( /* expression #1 */ )
{
return -1;
}
if ( /* expression #2 */ )
{
return -2;
}
return 1;
}
$return = doSomething();
switch ( $return )
{
case -1;
echo 'Error #1 Found';
break;
case -2;
echo 'Error #2 Found';
break;
default:
echo 'Success';
}
Error parameter
function doSomething( &$error )
{
if ( /* expression #1 */ )
{
$error = 'Something went wrong';
}
}
$error = false;
doSomething( $error );
if ( $error )
{
echo $error;
}
Error State
class Foo
{
private $error = false;
private $errorMsg;
public function doSomething()
{
if ( /* expression */ )
{
$this->setError( 'Something went wrong' );
}
}
public function isError()
{
return $this->error;
}
public function getErrorMsg()
{
return $this->errorMsg;
}
private function setError( $message )
{
$this->error = true;
$this->errorMsg = $message;
}
}
$f = new Foo();
$f->doSomething();
if ( $f->isError() )
{
echo $f->getErrorMsg();
}
You need to weigh the pros and cons of each before choosing a system (or combination of systems) for your project.
There isn't a common standard. Solution depends entirely on your particular needs.
Consider learning and using exceptions. They are not universal solution, but if used properly will go a long way to make your code more readable and understandable.
精彩评论