CODEIGNITOR ERROR HANDLING
CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it has an error logging class that permits error and debugging messages to be saved as text files.
In CodeIgniter, error handling is an important aspect to ensure that your application runs smoothly and you can easily debug any issues that arise. CodeIgniter has a built-in error handling class that you can utilize for this purpose. Here’s an overview of how you can handle errors in CodeIgniter:
1. Configuration
Enable Error Logging
To enable error logging in CodeIgniter, open the application/config/config.php
file and set the following configuration:
$config['log_threshold'] = 1;
The log_threshold
can be set to the following values:
- 0 = Disables logging, Error logging TURNED OFF
- 1 = Error Messages (including PHP errors)
- 2 = Debug Messages
- 3 = Informational Messages
- 4 = All Messages
2. Log File Path
By default, CodeIgniter logs error messages to application/logs
. Ensure that this directory is writable.
3. Error Views
You can customize the error views by creating a errors
directory within application/views
. Inside this directory, create the following subdirectories:
application/views/errors/cli
for command-line errorsapplication/views/errors/html
for web errors
For example, to create a custom 404 error page, create a file named error_404.php
in application/views/errors/html
.
4. Error Logging in Code
You can log custom error messages in your controllers or models using the log_message()
function. For example:
log_message('error', 'Some variable did not contain a value.');
log_message('debug', 'This is a debug message.');
log_message('info', 'The purpose of some variable is to provide some value.');
5. Displaying Errors
To display PHP errors on the screen, open the index.php
file at the root of your CodeIgniter installation and set the ENVIRONMENT
constant to development
:
6. Custom Error Handling
You can create a custom error handler by extending the CI_Exceptions
class. Create a file named MY_Exceptions.php
in the application/core
directory:
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Exceptions extends CI_Exceptions {
public function __construct() {
parent::__construct();
}
public function show_404($page = '', $log_error = TRUE) {
if ($log_error) {
log_message('error', '404 Page Not Found: ' . $page);
}
echo "Custom 404 Error Page";
exit(4); // EXIT_UNKNOWN_FILE
}
public function log_exception($severity, $message, $filepath, $line) {
// Custom logging logic here
log_message('error', 'Severity: ' . $severity . ' --> ' . $message . ' ' . $filepath . ' ' . $line);
}
}
7. Using Try-Catch Blocks
You can use try-catch blocks in your controllers or models to handle exceptions: