Advertisement
Google Ad Slot: content-top
CodeIgniter Error Handling
Error handling is very important in any application. In CodeIgniter, error handling helps developers to:
- Find issues in code.
- Show user-friendly error messages.
- Log errors for debugging later.
CodeIgniter provides multiple ways to handle errors, such as error reporting levels, error logging, exceptions, and custom error messages.
🔹 Step 1: Error Reporting Levels
In application/config/config.php, you can set the environment mode.
define('ENVIRONMENT', 'development');
- development → Shows all errors (good for debugging).
- testing → Limited error reporting.
- production → Hides sensitive errors from users.
👉 In index.php, you’ll see something like:
switch (ENVIRONMENT) {
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
}
🔹 Step 2: Showing Error Messages
Use CodeIgniter’s show_error() function:
if (!$user) {
show_error("User not found!", 404, "An Error Was Encountered");
}
Parameters:
- Message →
"User not found!" - Status Code →
404(Not Found) - Heading →
"An Error Was Encountered"
🔹 Step 3: Showing 404 Error
When a page is not found, you can use:
show_404();
Example:
public function view($page = 'home')
{
if (!file_exists(APPPATH . 'views/pages/' . $page . '.php')) {
show_404(); // Show custom 404 page
}
$this->load->view('pages/' . $page);
}
🔹 Step 4: Error Logging
CodeIgniter can log errors automatically.
In application/config/config.php:
$config['log_threshold'] = 1;
Log levels:
0= No logging1= Error messages2= Debug messages3= Informational messages4= All messages
👉 Logs are stored in:
application/logs/log-YYYY-MM-DD.php
Example of writing custom log:
log_message('error', 'Something went wrong!');
log_message('debug', 'Debugging message');
log_message('info', 'Just some information');
🔹 Step 5: Custom Error Pages
You can create a custom error page in:
application/views/errors/html/error_404.php application/views/errors/html/error_general.php
Example error_404.php:
<h1>Oops! Page not found.</h1> <p>The page you are looking for might have been removed.</p> <a href="<?= base_url(); ?>">Go Back Home</a>
🔹 Step 6: Handling PHP Exceptions
You can use try-catch blocks in controllers or models:
try {
$this->db->query("INVALID SQL QUERY");
} catch (Exception $e) {
log_message('error', $e->getMessage());
show_error("Database error occurred!");
}