PHP

Lesson 07

Error handling and exceptions

Handle exceptions at a clear boundary, log useful context, and return safe responses to users.

Good Code

public/index.php
<?php declare(strict_types=1);

try {
    $response = $router->dispatch($request);
    $response->send();
} catch (Throwable $error) {
    $logger->error('Unhandled request failure', [
        'path' => $request->path(),
        'exception' => $error,
    ]);

    http_response_code(500);
    echo 'Something went wrong.';
}

Bad Code

public/index.php
<?php

try {
    include $_GET['page'] . '.php';
} catch (Exception $error) {
    die($error->getMessage());
}

Review Notes

What to review

Good Code

The good version catches failures at the front controller boundary, logs internal details, and returns a generic response.

Bad Code

The bad version mixes routing with unsafe include behavior and sends raw exception messages to the browser.

Takeaways

  • Good PHP error handling separates developer diagnostics from user-facing responses.