PHP
PHP production error handling: useful logs without leaking details
Design PHP error handling with appropriate responses, private diagnostics, request references and observable recovery instead of exposed stack traces or silent failures.
A database outage should not expose credentials or file paths to a visitor. It also should not become an unexplained blank page that leaves the developer guessing.
Good production error handling serves two audiences: users need an honest outcome and a next step; maintainers need enough evidence to diagnose the failure.
Separate the response from the diagnostic record
Avoid returning a raw exception message in a public response. Exception details can contain query text, infrastructure names or internal paths. Conversely, swallowing every exception and returning success creates an application that appears healthy while losing work.
Choose an appropriate response for the failure and record a private diagnostic event. Use a reference that connects the public response to that event without exposing the event’s contents.
Configure production logging before an incident
Review the effective configuration for the web runtime, not just the CLI. An illustrative production baseline is:
display_errors = Off
display_startup_errors = Off
log_errors = On
error_reporting = E_ALL
Set the log destination, access permissions and retention policy for your environment. PHP’s error configuration reference explains these settings. Configure them at the appropriate runtime or deployment level: a setting executed inside a script cannot reliably handle failures that prevent that script from starting.
Verify that the configured destination actually receives a controlled error. A logging flag with an unwritable destination provides little operational value.
Handle failures at a clear boundary
A plain PHP JSON endpoint can establish a response boundary around its application work. This excerpt assumes it runs before output has started:
$requestId = bin2hex(random_bytes(16));
try {
// Application work goes here and sets $result.
$result = ['status' => 'ok'];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result, JSON_THROW_ON_ERROR);
} catch (Throwable $error) {
error_log(json_encode([
'event' => 'request_failed',
'request_id' => $requestId,
'exception_class' => get_class($error),
], JSON_THROW_ON_ERROR));
http_response_code(500);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'error' => 'Unable to complete this request.',
'reference' => $requestId,
], JSON_THROW_ON_ERROR);
}
This is a boundary pattern, not a complete framework exception handler. The sample intentionally avoids logging message bodies, request payloads or credentials. Add diagnostic fields only after deciding how to redact them and who can access them. Framework applications should normally use their existing reporting and rendering mechanisms.
A try/catch boundary does not intercept every possible PHP failure. Test the actual runtime and external monitoring rather than assuming every failure becomes this JSON response.
Distinguish expected and unexpected outcomes
| Outcome | Application behavior |
|---|---|
| Invalid form data | Return validation feedback without claiming the operation succeeded |
| Unauthenticated request | Follow the application’s authentication response contract |
| Forbidden operation | Reject it without exposing another user’s data |
| Missing record | Return the intended not-found result |
| Unexpected dependency failure | Report a server failure and record diagnostics |
Do not map every exception to a validation error. It misleads users and can hide incidents from operational monitoring.
Recovery needs a state model
Suppose an export fails after creating a partial file. Retrying should not serve the incomplete file as a finished result. Track pending, running, completed and failed states as appropriate, and make the user-facing message match the stored outcome.
For operations with multiple database writes, plan transaction boundaries. For external side effects, decide how to detect an earlier partial success before retrying. An HTTP error does not prove that nothing happened.
Verify the failure path
On staging, simulate an unavailable dependency and inspect the HTTP status, public response and private log. Confirm the reference matches and that no stack trace appears in the response.
Check the monitoring path too: who sees repeated failures, and how do they investigate them? Keep noisy repeated errors from obscuring a new incident, but avoid suppressing the underlying failure merely to make dashboards look clean.
For database boundaries, start with PDO prepared statements. For background processing, the Laravel queue troubleshooting guide explains why a failed attempt and a failed business outcome are not always the same thing.