Di seguito ho scritto un esempio che mostra come utilizzare le eccezioni in generale (non specifiche per la situazione) e più in basso qualcosa che è più specifico per voi (utilizzando ancora eccezioni). Questi primi due esempi gestiranno 1 errore alla volta. Il terzo esempio che ho fornito fornisce un esempio di come gestire più errori ed eccezioni.
La maggior parte della spiegazione è nei commenti del codice, in modo da essere sicuri di guardare attraverso di esso a fondo :)
Exception Handling Generale
<?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 />';
?>
standard classe Exception costruttore:
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]])
eccezioni personalizzate
Ora, in relazione questo per il tuo esempio, si potrebbe fare qualcosa in queste righe:
<?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
uscita del codice di cui sopra:
Error String: assert(): Assertion failed
Error Number: 2
File containing error: 18
Line with error: /var/www/test2.php
è possibile applicare i concetti di nidificazione try
/catch
dichiarazioni nel primo esempio di codice con questo secondo esempio di gestione degli errori personalizzati.
gestire più errori/eccezioni
<?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;
?>
Ovviamente è possibile modificare e adattare la classe errorLogger
per soddisfare specificamente le vostre esigenze.
uscita del codice di cui sopra:
There are 5 errors:
Array (
[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
)
)
Il codice di cui sopra consente di:
- eccezioni tiro e aggiungerli alla
errorLogger
- gestire eventuali situazioni non gestite dalle funzioni casuali che farebbe normalmente causare errori da visualizzare
- Aggiungi i tuoi errori manualmente
- errori trigger (http://uk3.php.net/trigger_error)
È quindi possibile visualizzare/log/qualunque cosa tutti gli errori in un momento successivo.
NB: Tutto il codice di cui sopra può essere copiato e incollato direttamente darti qualcosa di sperimentare
Mi piace molto questa libreria, penso che esaminerò il modo in cui funziona in modo più dettagliato e cerco di replicare le sue funzionalità nel mio framework. Grazie! –
* La validazione * è fantastica, la migliore che abbia mai visto. Complimenti a te! –
+1. Ho finalmente provato 'Respect \ Validation' su un progetto veloce ieri. Libreria molto utile! –