下面我编写了一个示例,向您展示了如何在一般情况下使用异常(非特定于您的情况)并进一步了解更具体的内容(仍然使用异常)。前两个示例将一次处理 1 个错误。我提供的第三个示例给出了如何处理多个错误和异常的示例。
大部分解释都在代码的注释中,所以一定要仔细阅读:)
一般异常处理
<?php
//Define some variables to work with
$var = false;
$var2 = false;
try { //Outer try
echo 'Do something here!<br />';
try { //Inner try
if($var !== true) { //Fail
throw new Exception('$var is not true',123); //Exception is thrown (caught 2 lines down)
}
} catch (Exception $e) { //Exception caught here
echo 'InnerError# '.$e->getCode().': '.$e->getMessage().'<br />'; //Exception handled (in this case printed to screen)
}
//Code is continuing here even after the exception was thrown
echo 'Do something else here!<br />';
if($var2 !== true) { //Fail
throw new Exception('$var2 is not true', 456); //Exception is thrown (caught 6 lines down)
}
//Code fails to run as the exception above has been thrown and jumps straight into the below catch
echo 'Do the third thing here!<br />';
} catch (Exception $e) { //Exception caught here
echo 'Error # '.$e->getCode().': '.$e->getMessage().' on line '.$e->getLine().' in '.$e->getFile().'<br />'; //Exception handled (in this case printed to screen)
}
//Code is continuting here even after both of the exceptions
echo 'Do even more stuff here!<br />';
?>
标准异常类构造函数:
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
自定义例外
现在,将此与您的示例相关联,您可以按照以下方式做一些事情:
<?php
class customException extends Exception { //Create a custom exception handler that allows you to pass more arguments in the constructor
public function __construct($errorString, $errorNumber, $errorFile, $errorLine) {
$this->message = $errorString; //Using the Exception class to store our information
$this->code = $errorNumber;
$this->file = $errorFile;
$this->line = $errorLine;
}
}
function err2Exception($errNo, $errStr, $errFile, $errLine) { //This function converts the error into an exception
throw new customException($errStr, $errNo, $errFile, $errLine); //Throw the customException
}
set_error_handler('err2Exception'); //Set the error handler to the above function
try {
assert(1==2); //This fails, calls the function err2Exception with the correct arguments, throws the error and is caught below
} catch (Exception $e) { //Error caught as an Exception here
//Echo out the details (or log them, or whatever you want to do with them)
echo 'Error String: '.$e->getMessage().'<br />';
echo 'Error Number: '.$e->getCode().'<br />';
echo 'File containing error: '.$e->getFile().'<br />';
echo 'Line with error: '.$e->getLine().'<br />';
}
?>
http://php.net/manual/en/function.set-error-handler.php
上述代码的输出:
错误字符串:assert():断言失败
错误编号:2
包含错误的文件:18
有错误的行:/var/www/test2.php
您可以将第一个代码示例中的嵌套try
/catch
语句的概念与自定义错误处理的第二个示例一起应用。
处理多个错误/异常
<?php
class errorLogger { //create an errorLogger class
private $errors; //Stores all errors
public function addError($errCode, $errMsg, $errFile = null, $errLine = null) { //Manually add an error
$this->errors[] = array( //Add to the error list
'code' => $errCode,
'message' => $errMsg,
'file' => $errFile,
'line' => $errLine
);
}
public function addException($exception) { //Add an exception to the error list
$this->errors[] = array( //Add to the error list
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine()
);
}
public function getErrors() { //Return all of the errors
return $this->errors;
}
public function numErrors() { //Return the number of errors
return count($this->errors);
}
}
$el = new errorLogger(); //New errorLogger
set_error_handler(array($el, 'addError')); //Set the default error handler as our errorLoggers addError method
set_exception_handler(array($el, 'addException')); //Set the default exception handler as our errorLoggers addException method
if(!is_numeric('a')) //Will fail
$el->addError('Invalid number', 1); //Adds a new error
if(($name = 'Dave') !== 'Fred') //Will fail
$el->addError('Invalid name ('.$name.')', 2, 'test.php', 40); //Adds another error
assert(1==2); //Something random that fails (non fatal) also adds to the errorLogger
try {
if('Cats' !== 'Dogs') //Will fail
throw new Exception('Cats are not Dogs', 14); //Throws an exception
} catch (Exception $ex) { //Exception caught
$el->addException($ex); //Adds exception to the errorLogger
}
trigger_error('Big bad wolf blew the house down!'); //Manually trigger an error
//throw new Exception('Random exception', 123); //Throw an exception that isn't caught by any try/catch statement
//(this is also added to the errorLogger, but any code under this is not run if it is uncommented as it isn't in a try/catch block)
//Prints out some
echo '<pre>'.PHP_EOL;
echo 'There are '.$el->numErrors().' errors:'.PHP_EOL; //Get the number of errors
print_r($el->getErrors());
echo '</pre>'.PHP_EOL;
?>
显然,您可以更改和调整errorLogger
课程以专门满足您的需求。
上述代码的输出:
有5个错误:
大批 (
[0] => Array
(
[code] => Invalid number
[message] => 1
[file] =>
[line] =>
)
[1] => Array
(
[code] => Invalid name (Dave)
[message] => 2
[file] => test.php
[line] => 10
)
[2] => Array
(
[code] => 2
[message] => assert(): Assertion failed
[file] => /var/www/test.php
[line] => 42
)
[3] => Array
(
[code] => 14
[message] => Cats are not Dogs
[file] => /var/www/test.php
[line] => 46
)
[4] => Array
(
[code] => 1024
[message] => Big bad wolf blew the house down!
[file] => /var/www/test.php
[line] => 51
)
)
上面的代码允许您:
然后,您可以稍后显示/记录/任何所有错误。
注意:以上所有代码都可以直接复制和粘贴,给你一些实验的东西