Skip to content

Error handling and logging in PHP applications

An error has two audiences: the person at the screen, who wants to know what to do next, and the team, who need to know what happened. This article shows how a PHP application serves both without telling one too much and the other too little.

  • Who it is forDevelopers
  • LevelIn depth
  • Reading timeabout 10 minutes
  • Last updated24 October 2026

What you will learn

  • How errors, exceptions and warnings differ in PHP, and why catch (Exception) does not catch everything
  • Where to catch an exception and where to let it pass
  • How a global handler produces a clear message and a complete log entry
  • Which log levels PSR-3 defines, and what has no place in a log

The short answer

Keep the two audiences strictly apart. The user receives a short, understandable message and a reference code. The team receives everything needed to find the cause in the log, under the same code: error class, message, file, line and context. In technical terms: in production, log errors rather than displaying them; turn warnings into exceptions; catch exceptions only where you can do something useful with them; install a global handler for everything else; log with a level and context, and keep secrets out.

Errors, exceptions and warnings

Since PHP 7, most serious problems are reported by throwing an Error, for example a TypeError when an argument has the wrong type. Your own exceptions and those of libraries, on the other hand, are Exceptions. Both implement the Throwable interface but form separate branches: Error does not extend Exception. Your own classes cannot implement Throwable directly; they extend Exception or one of its subclasses.

The three ways PHP reports a problem
BranchExamplesMeaning
ErrorTypeError, ValueError, DivisionByZeroError, UnhandledMatchErrorprogramming mistakes; according to the manual they generally require a fix to the code rather than handling at runtime
ExceptionRuntimeException, PDOException, ErrorException, your own classesexceptional situations the code can react to
Warning, noticeE_WARNING, E_NOTICE, E_DEPRECATEDreported but not thrown; the script carries on

The third row is the treacherous one. file_get_contents() on a missing file emits a warning and returns false; if nobody checks, the code carries on calculating with false. A custom error handler turns such messages into an ErrorException:

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI
<?php
declare(strict_types=1);

function netPrice(int $grossCents): int
{
    return intdiv($grossCents * 100, 119);
}

// catch (Exception) does not see engine errors: TypeError is an Error
try {
    try {
        netPrice('11900');               // string passed under strict_types
    } catch (Exception $e) {
        echo "never reached\n";
    }
} catch (Throwable $t) {
    echo get_class($t), ' is Exception? ', var_export($t instanceof Exception, true), "\n";
}

// Warnings are not thrown by default; an error handler turns them into exceptions
set_error_handler(function (int $level, string $message, string $file, int $line): bool {
    if (!(error_reporting() & $level)) {
        return false;                    // respect the configured error level
    }
    throw new ErrorException($message, 0, $level, $file, $line);
});

try {
    $config = file_get_contents(__DIR__ . '/missing.ini');
} catch (ErrorException $e) {
    echo 'caught: ', $e->getMessage(), "\n";
}
Output: TypeError is Exception? false — the inner catch (Exception) does not apply, only Throwable does. Then caught: file_get_contents(…): Failed to open stream: No such file or directory.

The error_reporting() check inside the handler matters: the handler is called regardless of the configured error level and has to decide for itself. According to the manual, some error types, including E_ERROR and E_PARSE, never reach a custom handler at all. For those, PHP’s own log is all that remains, which is one more reason to keep log_errors switched on.

Where to catch and where to let it pass

Catching an exception is only worthwhile if you can do something at that point. Four cases justify it:

  • Retry — after a temporary fault, with an upper limit.
  • Fall back — another route reaches the goal, such as a cached value.
  • Translate — a technical exception becomes a business exception the caller understands. Pass the original as $previous so the cause survives in the log.
  • Clean up — roll back a transaction, release a lock; finally is often the right place for that.

Anything that is none of these should travel on to the global handler. An empty catch block turns an error into a silent error, and silent errors cost more. For business cases, dedicated exception classes such as InvoiceNotFound pay off: they can be caught specifically and mapped to a suitable response, such as 404 or 422, while unknown technical errors end up as 500. How this looks in the flow of a form submission is described in PHP in the backend.

A last line of defence for everything else

set_exception_handler() registers a function for every exception nobody has caught. According to the manual, execution stops after that function has run, so it is the place for a log entry and a response, not for a restart. The following example shows both, together with a small log writer:

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI
<?php
declare(strict_types=1);

final class LogWriter
{
    private const SECRET_KEYS = ['password', 'token', 'iban', 'authorization'];

    /** @param array<string, mixed> $context */
    public function log(string $level, string $message, array $context = []): void
    {
        foreach ($context as $key => $value) {
            if (in_array(strtolower((string) $key), self::SECRET_KEYS, true)) {
                $context[$key] = '[redacted]';
            } elseif ($value instanceof Throwable) {
                $context[$key] = get_class($value) . ': ' . $value->getMessage()
                    . ' at ' . basename($value->getFile()) . ':' . $value->getLine();
            }
        }
        // one JSON line per entry: line breaks in user input cannot fake entries,
        // and invalid UTF-8 is replaced instead of silently emptying the entry
        $entry = ['level' => $level, 'message' => $message] + $context;
        fwrite(STDERR, json_encode($entry, JSON_INVALID_UTF8_SUBSTITUTE) . "\n");
    }
}

final class InvoiceNotFound extends RuntimeException {}

$log = new LogWriter();
$requestId = bin2hex(random_bytes(4));

set_exception_handler(function (Throwable $e) use ($log, $requestId): void {
    $log->log('error', 'Unhandled exception', ['request_id' => $requestId, 'exception' => $e]);
    echo "Sorry, that did not work. Please quote reference $requestId.\n";
});

$log->log('info', 'Login attempt', ['user' => "anna\nlevel=critical", 'password' => 'hunter2']);
throw new InvoiceNotFound('Invoice R-2026-0815 not found');
Output (abridged): one JSON entry per line, the password as [redacted], the line break in the user name as \n inside the entry; then the error entry with class, message, file and line, and for the user only Sorry, that did not work. Please quote reference … with the same code.

In a web application the handler also sets status code 500 and returns an error page rather than a line of text. The log writer is deliberately minimal. In real projects you would use a library implementing the PSR-3 interface; the principle is the same.

The settings that go with it

Recommended php.ini values; the bundled php.ini-development and php.ini-production templates set display_errors accordingly
SettingDevelopmentProduction
display_errorsOnOff — according to the manual, never on systems connected to the internet
log_errorsOnOn — the manual strongly advises logging instead of displaying
error_loganya file the web server user can write to, or syslog
error_reportingE_ALLE_ALL (default since PHP 8.0)

What belongs in the log

PSR-3, the logger recommendation of the PHP-FIG, defines eight levels and describes each one in a sentence in the interface code, some with examples. The right-hand column summarises these descriptions and adds examples of our own.

The eight log levels defined by PSR-3
LevelWhen
emergency, alertThe application is unusable, or someone has to step in immediately, for example because the database is unavailable.
criticalA component of the application is unavailable, or an unexpected exception has occurred.
errorAn operation has failed and needs attention.
warningUnusual but handled: a retry, a fallback.
notice, infoNotable events in normal operation: a login, an export created.
debugDetail for troubleshooting; usually switched off in production.

A message needs context: an array with the details that make the case distinguishable, such as order number, user ID or reference code. PSR-3 provides placeholders such as {order} in the message, which are filled from the context, and specifies that an exception in the context goes under the key exception. Keep the message text constant and the variable parts in the context; then identical errors can be counted.

A reference code per request links the user’s message to the log. It also helps when an operation passes through several systems, for example via a queue: pass it along and you can find every related entry.

What has no place in the log

The OWASP logging cheat sheet lists data that should not go into a log as it is, but should be removed, masked or hashed first. Among them:

  • passwords, session identifiers and access tokens
  • database connection strings, keys and other secrets
  • bank and card details
  • particularly sensitive personal data

The log writer in the example therefore replaces known keys with [redacted]. That is a safety net, not a substitute for care: the safest data is the data that never reaches the context. Pay particular attention to exception messages from database drivers and HTTP clients, which can contain whole requests including headers.

A second risk is log injection: if an input contains a line break, it can look like a separate entry in a plain-text log. OWASP recommends structured formats such as JSON. In the example, the user name anna\nlevel=critical therefore ends up as one value within a single line. The JSON_INVALID_UTF8_SUBSTITUTE option replaces invalid UTF-8 characters; without it, json_encode() returns false for such input and the entry would be empty.

A hypothetical example

The message “An error has occurred”

A member of staff reports that a new customer cannot be created. All she sees is a generic notice. Because there is a reference code underneath, the team finds the entry within seconds: a PDOException with SQLSTATE 23000, a violated uniqueness rule. The customer number already exists.

Technically the application was right; from a business point of view it failed, because a foreseeable case ended as a technical error. The fix was small: a check for an existing number and a message next to the field. The lesson applies generally: recurring entries at level error that are really user mistakes belong in input validation. A log that someone reads regularly reveals them.

Common misconceptions

The PHP manual states plainly that this setting should never be active on systems connected to the internet. It shows visitors paths, queries and sometimes credentials. Debugging happens in the log.

Errors such as TypeError or ValueError do not extend Exception. If you really want to catch everything, catch Throwable, and usually only in one central place.

It only suppresses the message. The function still returns false, and the information is then missing from the log as well.

A log nobody reads finds nothing, and every extra detail may be a secret. A few well-chosen entries with context are worth more.

Further sources

About the author

Fabian Lücker is managing partner of PHP Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design, and writes here about decisions that come up in real projects.