PHP 8: Modern PHP Development · Errors, Exceptions and Robust Code

Application-Wide Error Handling

Configure error reporting, convert warnings, and render safe error responses.

A robust app has one place that turns uncaught exceptions into responses and logs. In production: display_errors=Off, log_errors=On, error_reporting=E_ALL. Register set_exception_handler() (frameworks do this for you) to log with context and return a generic 500 page or problem-details JSON, and set_error_handler() to convert warnings/notices into ErrorException so they aren't silently ignored.

<?php
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
    if (!(error_reporting() & $severity)) {
        return false; // respect @-suppression and error_reporting
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
});

set_exception_handler(function (Throwable $e) use ($logger): void {
    $id = bin2hex(random_bytes(8));
    $logger->error($e->getMessage(), ['exception' => $e, 'error_id' => $id]);
    http_response_code(500);
    header('Content-Type: application/problem+json');
    echo json_encode(['title' => 'Internal Server Error', 'status' => 500, 'error_id' => $id]);
});

Common pitfalls

  • Leaving display_errors=On in production, leaking paths and stack traces.
  • Using the @ operator to hide errors instead of handling them.
  • Logging exceptions without request context (user, route, request ID).

Key points

  • Never display errors in production
  • Convert warnings into exceptions
  • Log with an error ID and show a generic message

Further reading: PHP manual: set_exception_handler

Practice questions

What php.ini settings should production use for errors?

Answer

display_errors=Off, display_startup_errors=Off, log_errors=On, and error_reporting=E_ALL, with logs shipped to a central system. Users see a generic error page with a reference ID.

Why convert warnings into ErrorException?

Answer

Warnings (e.g., failed file_get_contents) are easy to miss and let code continue with bad data. Converting them makes failures explicit and handled by normal exception flow.

Open in the app to mark lessons complete, take notes and track your progress.