Php Error Handling With Example

aimtocode

Error Handling

The error functions are used to deal with error handling and loging. The error functions allow us to define own error handling rules, and modify the way the errors can be logged.

The logging functions allow us to send messages directly to other machines, emails, or system logs. The error reporting functions allow us to customize what level and kind of error feedback is given.

List of various Error Handling functions:

Function Description
debug_backtrace() Generates a backtrace
debug_print_backtrace() Prints a backtrace
error_get_last() Returns the last error that occurred
error_log() Sends an error message to a log, to a file, or to a mail
error_reporting() Specifies which errors are reported
restore_error_handler() Restores the previous error handler
restore_exception_handler() Restores the previous exeception handler
set_error_handler() Sets user-defined error handler function
set_exception_handler() Sets a user-defined exception handler function
trigger_error() Creates a user-level error message
user_error() Alias of trigger_error()
debug_backtrace() Generates a backtrace

Understanding Error Levels

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

when there's a problem that prevents a script from running properly, the PHP engine triggers an error. Each error is represented by an integer value and an associated constant.

These are some of the common error levels:

Error Level Value Description
E_ERROR 1 A fatal run-time error, that can't be recovered from. The execution of the script is stopped immediately.
E_WARNING 2 A run-time warning. It is non-fatal and most errors tend to fall into this category. The execution of the script is not stopped.
E_NOTICE 8 A run-time notice. Indicate that the script encountered something that could possibly an error, although the situation could also occur when running a script normally.
E_USER_ERROR 256 A fatal user-generated error message. This is like an E_ERROR, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine.
E_USER_WARNING 512 A non-fatal user-generated warning message. This is like an E_WARNING, except it is generated by the PHP script using the function trigger_error() rather than the PHP. engine
E_USER_NOTICE 1024 A user-generated notice message. This is like an E_NOTICE, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine.
E_STRICT 2048 Not strictly an error, but triggered whenever PHP encounters code that could lead to problems or forward incompatibilities
E_ALL 8191 All errors and warnings, except of E_STRICT prior to PHP 5.4.0.


Read in Details

aimtocode