Skip to content

04: Structured Stream Errors

Read a local configuration file and classify a failed open using the stream error API. A structured error gives you a stable code and context for handling the failure.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable stream-errors.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/04-stream-errors/stream-errors.php
stream-errors.php
<?php
declare(strict_types=1);
$missingPath = sys_get_temp_dir() . '/settings-' . bin2hex(random_bytes(8)) . '.json';
$throwing = stream_context_create(['stream' => ['error_mode' => StreamErrorMode::Exception]]);
try {
file_get_contents($missingPath, context: $throwing);
} catch (StreamException $exception) {
foreach ($exception->getErrors() as $error) {
printf("Caught %s from %s\n", $error->code->name, $error->wrapperName);
}
}
stream_clear_errors();
$silent = stream_context_create([
'stream' => ['error_mode' => StreamErrorMode::Silent, 'error_store' => StreamErrorStore::All],
]);
if (file_get_contents($missingPath, context: $silent) === false) {
printf("Stored errors: %d\n", count(stream_last_errors()));
}
Caught OpenFailed from plainfile
Stored errors: 1

Exception mode exposes the collected errors through StreamException::getErrors(). Silent mode still returns the operation’s failure value. Set error_store to StreamErrorStore::All you can inspect its errors with stream_last_errors(); error_handler is another context option for reporting errors to a callback.

Create an empty file with tempnam() and read it with the same exception context. Confirm that you get an empty string and no exception. Remove the file in a finally block.

Continue with Limit Values with clamp().