Error Handling In PHP
Error handling is the process of catching errors raised by your program and then taking appropriate action. If you handle errors properly it can have many unforeseen consequences.
Need for error handling
Error Level
Error Level | Value | Description |
---|---|---|
E_ERROR | 1 | A fatal runtime error |
E_WARNING | 2 | A runtime warning, may not be fatal |
E_PARSE | 4 | A problem while parsing script(syntax errors) |
E_NOTICE | 8 | A possible run-time error, may also be generated by normal PHP script |
E_CORE_ERROR | 16 | A fatal error triggered during PHP engine startup |
E_CORE_WARNING | 32 | A non fatal error triggered during PHP engine startup |
E_COMPILE_ERROR | 64 | A fatal script error triggered during compilation |
E_COMPILE_WARNING | 128 | A non fatal script error triggered during compilation |
E_DEPRECATED | 8192 | Warning about deprecated PHP code |
Error handling – php.ini directives
Directive | Description |
---|---|
error_reporting | Which error levels to be triggered Default Value: E_ALL & ~E_NOTICE Development Value: E_ALL | E_STRICT Production Value: E_ALL & ~E_DEPRECATED |
display_errors | Whether to display errors on webpage Default & Development Value: On Production Value: Off |
log_errors | Whether to log errors in error log file Default and Development Value: On Production Value: Off |
error_log | Path of error log file |
Custom error handling
#Syntax set_error_handler set_error_handler('errorHandle'); #Syntax trigger_error trigger_error("File does not exist"); trigger_error("File does not exist", E_USER_WARNING)
Custom error settings
#Example error_reporting(E_ALL & ~E_NOTICE) error_reporting(0); // Turn off all error reporting error_reporting(-1); // Report all PHP errors ini_set("display_errors","Off"); error_log("file not found"); //Logged in default log file error_log("file not found","new_error.log"); //Logged in new_error.log