CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
Error handling is very important in any application. In CodeIgniter, error handling helps developers to:
CodeIgniter provides multiple ways to handle errors, such as error reporting levels, error logging, exceptions, and custom error messages.
In application/config/config.php
, you can set the environment mode.
define('ENVIRONMENT', 'development');
👉 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; }
Use CodeIgniter’s show_error() function:
if (!$user) { show_error("User not found!", 404, "An Error Was Encountered"); }
Parameters:
"User not found!"
404
(Not Found)"An Error Was Encountered"
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); }
CodeIgniter can log errors automatically.
In application/config/config.ph
p
:
$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');
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>
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!"); }