Error Handling and Logging

πŸ“˜ CodeIgniter πŸ‘ 29 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Error Handling and Logging in CodeIgniter (CodeIgniter 4)

CodeIgniter 4 provides a robust error handling and logging system that helps you debug during development and monitor issues in production.


1. Environment-Based Error Handling

CodeIgniter behaves differently based on environment mode.

Set Environment

In .env:

CI_ENVIRONMENT = development
EnvironmentBehavior
developmentDetailed error pages
productionGeneric error messages
testingMinimal output

2. Error Configuration Files

Main Error Config

app/Config/Exceptions.php

Controls:

  • Error views

  • Logging behavior

  • Custom exception handling


3. Display Errors (Development Only)

In app/Config/App.php:

public $displayErrors = true;

⚠️ Disable in production.


4. Error Views

Location:

app/Views/errors/

Examples:

  • error_404.php

  • error_exception.php

You can customize these pages.


5. Throwing Custom Errors

throw new \Exception('Something went wrong');

Or:

throw new \CodeIgniter\Exceptions\PageNotFoundException();

6. Logging System

Log Location

writable/logs/

Logging Levels

CodeIgniter supports PSR-3 log levels:

  • emergency

  • alert

  • critical

  • error

  • warning

  • notice

  • info

  • debug


Writing Logs

log_message('error', 'Database connection failed'); log_message('info', 'User logged in');

7. Log Configuration

File:

app/Config/Logger.php

Key settings:

public $threshold = 4; // Log everything up to error

8. Database Error Logging

Enable DB debug (development only):

'DBDebug' => true,

Disable in production to avoid sensitive info leaks.


9. Handling 404 Errors

$routes->set404Override(function () { return view('errors/custom_404'); });

10. Try–Catch Exception Handling

try { // risky code } catch (\Throwable $e) { log_message('error', $e->getMessage()); return redirect()->back()->with('error', 'Something went wrong'); }

11. Custom Error Controller

class ErrorController extends BaseController { public function show404() { return view('errors/custom_404'); } }

12. Production Best Practices

βœ… Disable detailed error display
βœ… Enable logging
βœ… Monitor logs regularly
❌ Never expose stack traces to users


Summary

  • Environment-based error handling

  • Built-in logging with PSR-3 support

  • Custom error pages & exceptions

  • Essential for debugging & security


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes