MySQL Error Handling

Error handling is the process to check errors in your program. In PHP it is very easy to handle errors because in browser it display file name, line number and small description about the error.

Error Handling using the die() function

If you want to open or read a text file in php. If the file is missing then in your page/ browser it will display Warning message. To avoid this you can use die() function.
if(!file_exists("myfile.txt")) {
  die("File not found");
} else {

In the above code if your file is missing the it will display a message "File not found".

Creating a Custom Error Handler

In PHP it is very simple to create a custom error handler function. The error handler function can accept 5 parameters out of which 2 are required and other 3 are optional.
The parameters are:
error_level: Required
error_message: Required
error_file: Optional
error_line: Optional
error_context: Optional

The different types of error the user-defined error handler can be used for are as follows:
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)

Error handler function

Now lets create a simple function to handel error in PHP.

//error handler function
function customError($errno, $errmsg) {
  echo "<b>Error:</b> [$errno] $errmsg";

//set error handler

//trigger error

The above code will display the following message.

Error: [8] Undefined variable: myVar

Disabling/ Turn off error reporting

You can also disable all errors or any particular error in your php page. You can use any one of the following to show or hide error message. The last one (E_ALL) will display all error, notice and warning etc.

# Turn off all error reporting

# Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

# Reporting E_NOTICE can be good too
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

# Report all errors except E_NOTICE
# This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

# Turn off deprecated error
error_reporting(E_ALL ^ E_DEPRECATED);

# Report all PHP errors

Other Related Posts

MySQL deprecated error
All deprecated functions and extensions in php 5.5

comments powered by Disqus