agyanadda@gmail.com

CodeIgniter 4 Error Handling and Logging

APIs and Advanced Topics 1 min read Updated Dec 3, 2026 Topic 27 of 30

Environments decide what users see

  • development — full error pages with code and stack trace, plus the Debug Toolbar at the bottom of each page
  • production — a simple "Whoops!" page; details go to the log

The Debug Toolbar

In development, the toolbar shows the time taken, queries run, views loaded, request data and logs. It is turned off in production.

Logging

log_message($level, $message, $context) writes to writable/logs/log-YYYY-MM-DD.log.

Levels: emergency, alert, critical, error, warning, notice, info, debug.

Use placeholders: log_message('error', 'Payment {id} failed', ['id' => $orderId]);

The $threshold in app/Config/Logger.php controls which levels are saved.

Custom error pages

Edit the views in app/Views/errors/html/ — for example error_404.php — to match your site design.

Exceptions

  • throw PageNotFoundException::forPageNotFound(); — 404
  • Wrap risky code (payments, external APIs) in try { } catch (\Throwable $e) { } and log the error

Check the log files first whenever something goes wrong on the live site.

Example

Example — Logging a failed API call PHP
<?php
use CodeIgniter\Exceptions\PageNotFoundException;

public function show(string $slug)
{
    $post = model('PostModel')->where('slug', $slug)->first();

    if (! $post) {
        throw PageNotFoundException::forPageNotFound("Post '$slug' not found");
    }

    try {
        $client   = service('curlrequest');
        $response = $client->get('https://api.example.com/views/' . $post['id'], ['timeout' => 3]);
        $views    = json_decode($response->getBody(), true)['views'] ?? 0;
    } catch (\Throwable $e) {
        log_message('error', 'View counter failed for post {id}: {msg}', ['id' => $post['id'], 'msg' => $e->getMessage()]);
        $views = 0;
    }

    return view('posts/show', compact('post', 'views'));
}

An unknown slug shows your 404 page. If the external API is down, the page still loads with 0 views, and a line like "ERROR - ... View counter failed for post 12: ..." is written to writable/logs.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Where are CodeIgniter 4 log files saved?

Exercise 2 True / False

The Debug Toolbar is shown in the production environment.

Exercise 3 Fill in the Blank

Write to the log with ___('error', 'Something failed')

Frequently Asked Questions

Edit app/Views/errors/html/error_404.php with your own HTML and links. You can also set a custom 404 handler in app/Config/Routes.php with $routes->set404Override('App\Controllers\Errors::show404').