I've written the following custom Exception handler:
namespace System\Exception;
class Handler extends \Exception {
public static function getException($e = null) {
if (ENVIRONMENT === 0 && is_object($e)) {
$message = "<p>";
$message .= "Exception: " . $e->getMessage();
$message .= "<br />File: " . $e->getFile();
$message .= "<br />Line: " . $e->getLine();
$message .= "<br />Trace: " . $e->getTrace();
$message .= "<br />Trace as string: " . $e->getTraceAsString();
$message .= "</p>";
} else {
$message = '<h1>Exception</h1>';
$message .= '<p>There was a problem.</p>';
}
#require_once('header.php');
echo $message;
#require_once('footer.php');
exit();
}
public static function getError($errno = 0, $errstr = null, $errfile = null, $errline = 0) {
if (ENVIRONMENT === 0) {
$message = "<p>";
$message .= "Error: " . $errstr;
$message .= "<br />File: " . $errfile;
$message .= "<br />Line: " . $errline;
$message .= "<br />Number: " . $errno;
$message .= "</p>";
} else {
$message = '<h1>Error</h1>';
$message .= '<p>There was a problem.</p>';
}
#require_once('header.php');
echo $message;
#require_once('footer.php');
exit();
}
public static function getShutdown() {
$last_error = error_get_last();
if ($last_error['type'] === E_ERROR) {
self::getError(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
}
}
}
and have indicated that I want to use this class and its methods for processing all exceptions and errors generated by the system in the following way:
set_exception_handler(array("System\Exception\Handler", "getException"));
set_error_handler(array("System\Exception\Handler", "getError"), -1 & ~E_NOTICE & ~E_USER_NOTICE);
register_shutdown_function(array("System\Exception\Handler", "getShutdown"));
I have also indicated that I don't want errors to be displayed on the screen and wand to report all of the errors:
ini_set('display_errors', 'Off');
error_reporting(-1);
My question now is - do I still need to use the try { } catch () { } statement in order to catch any exceptions and errors? I know that the above is most probably not a bullet proof, but seem to be working so far without any try / catch statement by processing all uncaught exceptions and errors.
Also - is there any disadvantage by using custom exception handler and letting it catch all uncaught exceptions rather than doing this via try {} catch (i.e. performance / security etc.)?
You don't have to, but you cannot recover - using try/catch gives you the advantage of reacting to particular exception (for example file not found in some_custom_session_handling() might be a good place to use try/catch and log out such user without session file).
So the advantage is that you have prettier messages. The downside is that you treat exceptions always the same. It's not bad in itself, and should not degradate performance or security, but it misses the point of using exceptions in the first place.
However, it does not exclude using try/catch where you might want them, so I'd say it's a good failover solution, but should be avoided as a try/catch replacement
As jderda said, be using your aproach you are missing the point of exceptions: to check for any errors in the upper levels of your code and react to them - halt or treat the exception and move on. Your aproach is fine when you want to, for example, log all uncaught exceptions
Related
I have this kind of loop. On each iteration it should include a file, Included files can come with errors. Once some of included files gets an error the whole process of getting lost. How to prevent breaking of the process?
I tried this try catch but it errors from included files still cause stopping execution of file.
Thanks
foreach ($li_arrays as $index => $li_array) {
if($index == 0){
try {
require 'update.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}
elseif ($index == 1){
try {
require 'update1.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}else{
try {
require 'update2.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}
Errors in php are not recoverable, so they will always lead to the termination of your script.
I am not even sure that you are even talking about Errors, though if you are, this is the answer to your question.
Another thing to be aware of:
Require will throw an E_COMPILE_ERROR if the required file doesn't exist, which is also something you won't be able to catch.
If you don't want to terminate if the script isn't found, use include instead.
At the end I changed "require" with "include" and used this try-catch approach inside each included file.
$attempts = 0;
do {
try
{
////PHP code ///
} catch (Exception $e) {
echo "\n\n======EXCEPTION======\n\n";
var_dump($e);
$attempts++;
sleep(30);
continue;
}
break;
} while($attempts < 5);
I have code that causes 2 errors, 1 from the php function pg_query_params because I've input an invalid query, and the Exception that I throw when the result of that function is false:
if (!$res = pg_query_params($this->sql, $this->args)) {
// note pg_last_error seems to often not return anything
$msg = pg_last_error() . " " . $this->sql . PHP_EOL . " Args: " . var_export($this->args, true);
throw new \Exception("Query Execution Failure: $msg");
}
Then I have error handler code which logs the errors and is supposed to echo them. Both errors are logged, but only the last (the thrown exception) is echoed. I'd like both echoed, as the first contains helpful debugging info. I don't understand why both aren't, as I've done some debugging and echo is called for both errors. Is it something related to output buffering or a concurrency issue?
Here is a shortened version of my error handler code. The throwableHandler method is registered with set_exception_handler() and the phpErrorHandler method with set_error_handler(). I haven't included generateMessageBodyCommon() but it simply adds error info to the message body:
private function handleError(string $messageBody, int $errno)
{
// echo
if ($this->echoErrors) {
$messageBody .= 'inside echo'; // this goes into the log file for both errors
echo nl2br($messageBody, false);
}
// log
#error_log($messageBody, 3, $this->logPath);
}
public function throwableHandler(\Throwable $e)
{
$message = $this->generateMessageBodyCommon($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
$message .= PHP_EOL . "Stack Trace:" . PHP_EOL . $e->getTraceAsString();
$this->handleError($message, $e->getCode(), $exitPage);
}
public function phpErrorHandler(int $errno, string $errstr, string $errfile = null, string $errline = null)
{
$message = $this->generateMessageBodyCommon($errno, $errstr, $errfile, $errline) . PHP_EOL . "Stack Trace:". PHP_EOL . $this->getDebugBacktraceString();
$this->handleError($message, $errno, false);
}
Be careful with '#' -> #error_log($messageBody, 3, $this->logPath);
PHP supports one error control operator: the at sign (#). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
http://php.net/manual/en/language.operators.errorcontrol.php
Error level :
error_reporting(E_ALL);
http://www.php.net/manual/en/function.error-reporting.php
error_reporting — Sets which PHP errors are reported
I use Yii2 with my framework because I like ActiveRecord and QueryBuilder.
Yii2 Official docs
describes how to use it.
It works, but Yii2 takes all control of PHP exceptions and warnings in ErrorHandler.php
/**
* Register this error handler
*/
public function register()
{
ini_set('display_errors', false);
set_exception_handler([$this, 'handleException']);
if (defined('HHVM_VERSION')) {
set_error_handler([$this, 'handleHhvmError']);
} else {
set_error_handler([$this, 'handleError']);
}
if ($this->memoryReserveSize > 0) {
$this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
}
register_shutdown_function([$this, 'handleFatalError']);
}
I don't know how to deal with it.
For example, I have DBException form Yii. If I set my own set_exception_handler, it will have very poor information about exception: only code and message. It will be very difficult to debug it without prepared query, query parameters, etc.
If I use Yii2's exception handler - I have to rewrite all my framework with Yii2 exceptions. Thats not good and I don't really like Yii2 letters and exception templates. All I need from Yii2 is work with DB.
Do you have any ideas how can I solve this situation?
I realized, that Yii's Database Exception has all information about request and error. Also that Exception has some additional methods for another info. Thats enough to controll all Exceptions and errors by my Framework as usual.
So I rewrited all handlers again to my handlers
spl_autoload_register(array("MyClass", 'autoload'));
set_exception_handler(['MyClass','exceptionHandler']);
set_error_handler(['MyClass','errorHandler']);
and collect all usefull information to error body
$body .= "Error: " . $e->getMessage() . PHP_EOL;
$body .= "File: " . $e->getFile() . ":" . $e->getLine() . PHP_EOL;
$body .= "Trace:" .$e->getTraceAsString() . PHP_EOL;
$prev = $e->getPrevious();
if ($prev) {
$body .= "Next To: ";
$body .= get_class($prev)." ".PHP_EOL;
$body .= $prev->getMessage();
}
if ($e instanceof yii\db\Exception) {
$body .= "Additional Info: " . (print_r($e->errorInfo, true));
}
I am handling errors with the following script:
<?php # config.inc.php
// This script establishes email default settings.
// This script determines how errors are handled.
// Email Settings
$site['from_name'] = 'x'; // from email name
$site['from_email'] = 'x#x.com'; // from email address
// Just in case we need to relay to a different server,
// provide an option to use external mail server.
$site['smtp_mode'] = 'enabled'; // enabled or disabled
$site['smtp_host'] = 'mail.x.com';
$site['smtp_port'] = null;
$site['smtp_username'] = 'admin#x.com';
$site['smtp_password'] = 'x';
// Error handling:
// Flag variable for site status:
$live = TRUE;
ini_set('display_errors','On');
error_reporting(E_ALL);
// Error log email address:
$admin_email = 'x#x.com';
date_default_timezone_set('America/New_York');
// Create the error handler.
function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) {
global $live, $admin_email;
// Build the error message.
$message = "An error occurred in script '$e_file' on line $e_line: \n<br />$e_message\n<br />";
// Add the date and time.
$message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />";
// Append $e_vars to the $message.
$message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n<br />";
if ($live) { // Don't show the specific error.
error_log ($message, 1, $admin_email); // Send email.
// Only print an error message if the error isn't a notice.
if ($e_number != E_NOTICE) {
echo '<div id="Error">A system error occurred. An administrator has been notified. We apologize for the inconvenience.</div><br />';
}
} else { // Development (print the error).
echo '<div id="Error">' . $message . '</div><br />';
}
} // End of my_error_handler() definition.
// Use my error handler.
set_error_handler ('my_error_handler');
?>
If I include this script in a script with an error, the error does not get displayed. If I comment out the call to set_error_handler(), the error does get displayed. What am I doing wrong that could be causing this behavior?
From the docs http://php.net/manual/en/function.set-error-handler.php
It is important to remember that the standard PHP error handler is
completely bypassed for the error types specified by error_types
unless the callback function returns FALSE.
Make your handler return FALSE
I am using the following error handling function, which emails the error to $admin_email if the site is live ($live==TRUE). My host now requires SMTP authentication. Am I correct in assuming I must remove the call to error_log() and send mail using either the PEAR mail package or PHPMailer?
// Create the error handler.
function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) {
global $live, $admin_email;
// Build the error message.
$message = "An error occurred in script '$e_file' on line $e_line: \n<br />$e_message\n<br />";
// Add the date and time.
$message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />";
// Append $e_vars to the $message.
$message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n<br />";
if ($live) { // Don't show the specific error.
echo('<p>sending email</p>');
error_log ($message, 1, $admin_email); // Send email.
// Only print an error message if the error isn't a notice.
if ($e_number != E_NOTICE) {
echo '<div id="Error">A system error occurred. An administrator has been notified. We apologize for the inconvenience.</div><br />';
}
} else { // Development (print the error).
echo '<div id="Error">' . $message . '</div><br />';
}
return FALSE;
} // End of my_error_handler() definition.
The mail function does not use authorization. I think on windows you can set php to use smtp by default in the php.ini file.