Skip to content

feat: refresh exception reporting across HTML, CLI, and API responses - #10829

Open
paulbalandan wants to merge 1 commit into
codeigniter4:4.8from
paulbalandan:new-exception-handler-4.8
Open

paulbalandan wants to merge 1 commit into
codeigniter4:4.8from
paulbalandan:new-exception-handler-4.8

Conversation

@paulbalandan

Copy link
Copy Markdown
Member

Description

Refresh detailed exception reporting for 4.8 and normalize stack frames across the HTML error page, CLI output, API responses, and logs. Each frame now keeps the call, arguments, and source location aligned.

  • The HTML error page adds a selectable stack trace, highlighted source excerpts, expandable argument previews, editor links, and a light/dark toggle. It retains request, response, and runtime diagnostics and makes the error report copyable as Markdown.
  • The CLI shows a source excerpt below the exception location, keeps path:line links clickable, and wraps long calls to the terminal width.
  • Diagnostic output masks credential headers and configured sensitive fields. Query, form, and cookie values are opt-in. Copy Details respects SHOW_DEBUG_BACKTRACE.
  • Detailed API responses retain trace, with normalized call and source metadata. Frame arguments have been removed, and trace is empty when SHOW_DEBUG_BACKTRACE is disabled.

The user guide, error-page screenshot, changelog, and 4.8 upgrade guide have been updated.

Try it locally

Demo files and commands for HTML, JSON, and CLI errors

Use these files in a local checkout. The demo controller deliberately throws on the home page.

app/Config/Routes.php

<?php

use CodeIgniter\Router\RouteCollection;

/** @var RouteCollection $routes */
$routes->get('/', 'Home::index');
$routes->match(['GET', 'POST'], 'demo/diagnostics', 'Home::diagnostics');

app/Controllers/Home.php

<?php

namespace App\Controllers;

use Composer\Autoload\ClassLoader;
use Config\Database;
use LogicException;

class Home extends BaseController
{
    public function index(): string
    {
        $demo = $this->request->getGet('demo');

        if ($demo === 'frames') {
            $this->throwWithDeepTrace(25);
        }

        if ($demo === 'origins') {
            array_map(static function (string $prefix): void {
                (new ClassLoader())->addPsr4($prefix, APPPATH);
            }, ['InvalidPrefix']);
        }

        if ($demo === 'causes') {
            $cause = new LogicException('Original cause.');

            for ($index = 1; $index <= 12; $index++) {
                $cause = new LogicException(sprintf('Exception %d in the chain.', $index), previous: $cause);
            }

            throw $cause;
        }

        if ($demo === 'sql') {
            $db = Database::connect([
                'DBDriver' => 'SQLite3',
                'database' => ':memory:',
                'DBDebug'  => true,
            ], false);

            $db->query('SELECT id, total FROM invoices');
        }

        $this->bar();

        return view('welcome_message');
    }

    public function bar()
    {
        throw new LogicException("I'm here!", previous: new LogicException('Previous exception'));
    }

    public function diagnostics(): never
    {
        $this->response->setHeader('X-Demo-Response', 'Exception diagnostics');

        throw new LogicException('Inspect the Request and Response diagnostics below.');
    }

    private function throwWithDeepTrace(int $depth): never
    {
        if ($depth === 0) {
            throw new LogicException('This exception has more stack frames than the page can display.');
        }

        $this->throwWithDeepTrace($depth - 1);
    }
}

app/Commands/ThrowException.php

<?php

namespace App\Commands;

use CodeIgniter\CLI\AbstractCommand;
use CodeIgniter\CLI\Attributes\Command;
use LogicException;
use Override;
use RuntimeException;

#[Command(name: 'demo:throw', description: 'Throws a chained exception to preview CLI error output.', group: 'Demo')]
final class ThrowException extends AbstractCommand
{
    #[Override]
    protected function execute(array $arguments, array $options): never
    {
        throw new RuntimeException('The demo command failed.', previous: new LogicException('The original cause.'));
    }
}

Run the demos

Start the development server.

php spark serve
Open in a browser What to inspect
http://localhost:8080/ A chained exception, light/dark toggle, and Copy Details
http://localhost:8080/?demo=origins Application, vendor, closure, and internal frames
http://localhost:8080/?demo=frames The hidden-frame count
http://localhost:8080/?demo=causes A long chain of previous exceptions
http://localhost:8080/?demo=sql A missing-table error with the PHP SQLite3 extension enabled
http://localhost:8080/demo/diagnostics Request diagnostics and the X-Demo-Response header

Request the JSON response and check the HTTP status and normalized trace.

curl -i -H 'Accept: application/json' 'http://localhost:8080/?demo=origins'

Run the CLI demo to inspect the source excerpt and wrapped backtrace. It exits with status 1.

php spark demo:throw

Checklist

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value (without duplication)
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@carson-codeigniter4 carson-codeigniter4 Bot added the 4.8 PRs that target the `4.8` branch. label Nov 26, 2026
@paulbalandan paulbalandan added the enhancement PRs that improve existing functionalities label Nov 26, 2026
@paulbalandan
paulbalandan force-pushed the new-exception-handler-4.8 branch 2 times, most recently from e0d5b94 to 15bbb26 Compare November 26, 2026 07:41
@paulbalandan
paulbalandan force-pushed the new-exception-handler-4.8 branch from 15bbb26 to 518dc00 Compare November 26, 2026 08:18

@michalsn michalsn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks pretty cool. Not sure if I would prefer the tabs (like we used to have) in place of "Diagnostics"... but maybe this is a matter of preference.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

4.8 PRs that target the `4.8` branch. enhancement PRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants