In previous versions of PHP, errors were treated quite differently than exceptions. An error was something that was produced in the engine and as long as it was not fatal, it could be handled by a user-defined function.
The problem was that there were several errors that were fatal and that could not be handled by a user-defined error handler. This meant that you couldn’t handle fatal errors in PHP gracefully. There were several side-effects that were problematic, such as the loss of runtime context, destructors would not be called and dealing with them was clunky. In PHP 7, fatal errors are now exceptions and we can handle them very easily. Fatal errors result in an error exception being thrown. You need to handle non-fatal errors with an error-handling function.
Here is an example of catching a fatal error in PHP 7.1. Notice how the non-fatal error is not caught.
try { // this will generate notice that would not be caught echo $someNotSetVariable; // fatal error that now actually is caught someNoneExistentFunction(); } catch (Error $e) { echo "Error caught: " . $e->getMessage(); } op: Notice: Undefined variable: someNotSetVariable on line 3 Error caught: Call to undefined function someNoneExistentFunction()
This script will output a notice error for the attempt to access an invalid variable. Trying to call a function that does not exist would result in a fatal error in earlier versions of PHP, but in PHP 7.1 you can catch it. Here is the output for the script:
PHP has a lot of constants that are used in relation to errors. These constants are used when configuring PHP to hide or display errors of certain classes.
The set_error_handler() function is used to tell PHP how to handle standard engine errors that are not instances of the Error exception class. You cannot use an error-handler function for fatal errors. Error exceptions must be handled with try/catch statements. set_error_handler() accepts a callable as its parameter. Callables in PHP can be specified in two ways: either by a string denoting the name of a function or by passing an array that contains an object and the name of a method (in that order). You can specify protected and private methods as the callable in an object. You can also pass null to tell PHP to revert to the usage of the standard error-handling mechanism. If your error handler does not terminate the program and returns, your script will continue executing at the line after the one where the error occurred.
You can write your own function to handling any error. PHP provides you a framework to define error handling function. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context) −
error_function(error_level,error_message, error_file,error_line,error_context);
error_reporting( E_ALL ); function handleError($errno, $errstr,$error_file,$error_line) { echo "Error: [$errno] $errstr - $error_file:$error_line"; echo "
"; echo "Terminating PHP Script"; die(); } //set error handler set_error_handler("handleError"); //trigger error myFunction();
function myCustomErrorHandler(int $errNo, string $errMsg, string $file, int $line) { echo "Wow my custom error handler got #[$errNo] occurred in [$file] at line [$line]: [$errMsg]"; } set_error_handler('myCustomErrorHandler'); try { what; } catch (Throwable $e) { echo 'And my error is: ' . $e->getMessage(); } op: Error #[2] occurred in [php shell code] at line [3]: [Use of undefined constant what - assumed 'what' (this will throw an Error in a future version of PHP)]
When you application reaches production, you want to hide all system error messages while in production and your code must run without generating warnings or messages. If you are going to show an error message, make sure that it is the one you’ve generated and that it does not include information that could help an attacker break into your system.
In your development environment, you want all errors to be displayed so that you can fix all the issues they relate to, but while in production, you want to suppress any system messages being sent to the user.
To accomplish this, you need to configure PHP using the following settings in your php.ini file:
The best practice is to handle errors in your application gracefully. In production, you should rather log unhandled errors instead of allowing them to be displayed to the user. The error_log() function can be used to send a message to one of the defined error handling routines. You can also use the error_log() function to send emails, but personally, would rather use a good solution for logging errors and receiving notifications when an error occurs like Sentry or Rollbar.
There is a thing called Error Control Operator – the at-sign (@) – that in the essence can ignore and suppress errors. The usage is very easy – just prepend any PHP expression with at-sign and generated error will be ignored. Although using this operator may look interesting, I urge you not to do that. I like to call it the living relict from the past.
Exceptions are a core part of object-oriented programming and were first introduced in PHP 5.0. An exception is a program state that requires special processing because it’s not running in an expected manner. You can use an exception to change the flow of your program, for example, to stop doing something if certain preconditions are not met.
class MyCustomException extends Exception { } function throwMyCustomException() { throw new MyCustomException('There is something wrong.'); } try { throwMyCustomException(); } catch (MyCustomException $e) { echo "Your custom exception caught "; echo $e->getMessage(); } catch (Exception $e) { echo "PHP base exception caught"; }
class MyCustomException extends Exception { } class MyAnotherCustomException extends Exception { } try { throw new MyAnotherCustomException; } catch (MyCustomException | MyAnotherCustomException $e) { echo "Caught : " . get_class($e); }
class MyCustomException extends Exception { } function throwMyCustomException() { throw new MyCustomException('There is something wrong.'); } try { throwMyCustomException(); } catch (MyCustomException $e) { echo "Your custom exception caught "; echo $e->getMessage(); } catch (Exception $e) { echo "PHP base exception caught"; } finally { echo "I'm always here"; }
Any exception that is not caught results in a fatal error. If you want to respond gracefully to exceptions that are not caught in catch blocks, you’ll need to set a function as the default exception handler.
To do so, you use the set_exception_handler() function, which accepts a callable as its parameter. Your script will terminate after the callable has executed.
The function restore_exception_handler() will revert the exception handler to its previous value.
class MyCustomException extends Exception { } function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); try { throw new Exception('Uncaught Exception'); } catch (MyCustomException $e) { echo "Your custom exception caught "; echo $e->getMessage(); } finally { echo "I'm always here"; } print "Not executed";
function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n";
Total : 27273
Today :9
Today Visit Country :