Stream context options — Stream error handling context option listing
The options under the stream key are available for
all wrappers. They control how the errors of stream operations
that use the context are reported.
See Stream Errors for an overview.
The values of these options are not validated when the context is
created. If an operation reports an error and
error_mode is not a
StreamErrorMode, error_store
is not a StreamErrorStore, or
error_handler is not a valid
callable, a TypeError is thrown.
| Version | Description |
|---|---|
| 8.6.0 |
Added error_mode,
error_store and
error_handler.
|
Note:
These options cannot be set with stream_context_set_default(), which throws a ValueError if these options are passed.
Note:
Only errors of the stream layer are affected. Other errors of a function, such as a ValueError or TypeError for an invalid argument, are thrown as usual.
Example #1 Throwing exceptions for stream errors
<?php
$context = stream_context_create([
'stream' => [
'error_mode' => StreamErrorMode::Exception,
],
]);
try {
$stream = fopen('/nonexistent/file.txt', 'r', false, $context);
} catch (StreamException $exception) {
echo $exception->getMessage(), PHP_EOL;
foreach ($exception->getErrors() as $error) {
echo $error->wrapperName, ': ', $error->code->name, PHP_EOL;
}
}The above example will output:
Failed to open stream: No such file or directory plainfile: OpenFailed
Example #2 Retrieving errors without diagnostics
<?php
$context = stream_context_create([
'stream' => [
'error_mode' => StreamErrorMode::Silent,
],
]);
$stream = fopen('/nonexistent/file.txt', 'r', false, $context);
var_dump($stream);
foreach (stream_last_errors() as $error) {
echo $error->code->name, ': ', $error->message, PHP_EOL;
}The above example will output:
bool(false) OpenFailed: Failed to open stream: No such file or directory
Example #3 Receiving errors in an error handler
<?php
$context = stream_context_create([
'stream' => [
'error_mode' => StreamErrorMode::Silent,
'error_store' => StreamErrorStore::None,
'error_handler' => function (array $errors): void {
print_r($errors);
},
],
]);
fopen('/nonexistent/file.txt', 'r', false, $context);The above example will output:
Array
(
[0] => StreamError Object
(
[code] => StreamErrorCode Enum
(
[name] => OpenFailed
)
[message] => Failed to open stream: No such file or directory
[wrapperName] => plainfile
[severity] => 2
[terminating] => 1
)
)