-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-handling.php
More file actions
243 lines (193 loc) · 7.71 KB
/
error-handling.php
File metadata and controls
243 lines (193 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
/**
* Error Handling Examples
*
* This file demonstrates error handling patterns using attempt() and handleError()
* from phunkie/effect IO. These patterns enable functional error recovery and
* composition while maintaining type safety.
*/
use function Phunkie\Effect\Functions\io\io;
use function Phunkie\Streams\Functions\file\exists;
use function Phunkie\Streams\Functions\file\readFileContents;
use function Phunkie\Streams\Functions\file\readLines;
use function Phunkie\Streams\Functions\file\writeFileContents;
use Phunkie\Streams\IO\File\Path;
require_once dirname(__FILE__, 2) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/printLn.php';
echo "=== Error Handling Examples ===\n\n";
// Example 1: Basic attempt() usage
echo "1. Using attempt() to catch errors:\n";
$nonExistentFile = new Path('/nonexistent/file.txt');
$attemptResult = readFileContents($nonExistentFile)
->attempt()
->unsafeRunSync();
// Validation provides getOrElse for safe value extraction
$content = $attemptResult->getOrElse("File not found - using fallback");
echo " Result: $content\n\n";
// Example 2: Pattern matching on Validation
echo "2. Pattern matching with Validation:\n";
$result = readFileContents($nonExistentFile)
->attempt()
->unsafeRunSync();
// Check if it's a success or failure
$isSuccess = $result->getOrElse(null) !== null;
echo " Is success: " . ($isSuccess ? "yes" : "no") . "\n";
echo " Value or default: " . $result->getOrElse("default value") . "\n\n";
// Example 3: handleError() for recovery
echo "3. Using handleError() to recover from errors:\n";
$recovered = readFileContents($nonExistentFile)
->handleError(fn ($error) => "Error recovered: " . $error->getMessage())
->unsafeRunSync();
echo " Recovered value: $recovered\n\n";
// Example 4: handleError with fallback file
echo "4. Fallback to alternative file:\n";
$primaryFile = new Path('/nonexistent/primary.txt');
$fallbackFile = new Path(__FILE__); // This file exists
$withFallback = readFileContents($primaryFile)
->handleError(function ($error) use ($fallbackFile) {
return readFileContents($fallbackFile)
->map(fn ($content) => substr($content, 0, 100) . "...")
->unsafeRunSync();
})
->unsafeRunSync();
echo " Got content from fallback: " . substr($withFallback, 0, 50) . "...\n\n";
// Example 5: Chaining with error handling
echo "5. Chaining operations with error handling:\n";
$tempFile = new Path(sys_get_temp_dir() . '/error_test.txt');
$chainedResult = writeFileContents($tempFile, "Original content")
->flatMap(fn ($_) => readFileContents($tempFile))
->map(fn ($content) => strtoupper($content))
->handleError(fn ($e) => "ERROR: " . $e->getMessage())
->unsafeRunSync();
echo " Result: $chainedResult\n";
// Clean up
if (file_exists($tempFile->toString())) {
unlink($tempFile->toString());
}
echo "\n";
// Example 6: attempt() in a chain
echo "6. Using attempt() in a pipeline:\n";
$pipelineResult = writeFileContents($tempFile, "Test content")
->flatMap(fn ($_) => readFileContents($tempFile))
->attempt()
->map(function ($validation) {
// Process the Validation
return $validation->getOrElse("Failed to read");
})
->unsafeRunSync();
echo " Pipeline result: $pipelineResult\n";
// Clean up
if (file_exists($tempFile->toString())) {
unlink($tempFile->toString());
}
echo "\n";
// Example 7: Multiple error handling strategies
echo "7. Multiple error handling strategies:\n";
// Strategy 1: Provide default value
$strategy1 = readFileContents($nonExistentFile)
->attempt()
->map(fn ($v) => $v->getOrElse("DEFAULT"))
->unsafeRunSync();
echo " Strategy 1 (default): $strategy1\n";
// Strategy 2: Recover with computation
$strategy2 = readFileContents($nonExistentFile)
->handleError(fn ($e) => "Computed fallback: " . date('Y-m-d H:i:s'))
->unsafeRunSync();
echo " Strategy 2 (computed): $strategy2\n";
// Strategy 3: Transform error to success
$strategy3 = readFileContents($nonExistentFile)
->handleError(fn ($e) => "Error was: " . get_class($e))
->unsafeRunSync();
echo " Strategy 3 (transform): $strategy3\n\n";
// Example 8: Validating operations
echo "8. Validation with file operations:\n";
$testFile = new Path(sys_get_temp_dir() . '/validation_test.txt');
$validationResult = writeFileContents($testFile, "Valid content")
->flatMap(fn ($_) => exists($testFile))
->flatMap(function ($fileExists) use ($testFile) {
if (!$fileExists) {
return io(fn () => throw new \RuntimeException("File should exist!"));
}
return readFileContents($testFile);
})
->handleError(fn ($e) => "Validation failed: " . $e->getMessage())
->unsafeRunSync();
echo " Validation result: $validationResult\n";
// Clean up
if (file_exists($testFile->toString())) {
unlink($testFile->toString());
}
echo "\n";
// Example 9: Composing error handlers
echo "9. Composing multiple error handlers:\n";
function safeReadFile(Path $path): string
{
return readFileContents($path)
->handleError(function ($e) use ($path) {
// First level: Try to provide context
if ($e instanceof \RuntimeException) {
return "RuntimeException reading {$path->toString()}";
}
return "Unknown error reading file";
})
->unsafeRunSync();
}
$composedResult = safeReadFile($nonExistentFile);
echo " Composed result: $composedResult\n\n";
// Example 10: Error handling with resource cleanup
echo "10. Error handling ensures resource cleanup:\n";
$cleanupFile = new Path(sys_get_temp_dir() . '/cleanup_test.txt');
// Create a file that we'll try to read with an error in processing
writeFileContents($cleanupFile, "Content to process")
->unsafeRunSync();
$processWithError = readFileContents($cleanupFile)
->map(function ($content) {
// Simulate an error during processing
if (strlen($content) > 0) {
throw new \RuntimeException("Processing error!");
}
return $content;
})
->handleError(fn ($e) => "Caught error: " . $e->getMessage())
->unsafeRunSync();
echo " Processed with error handling: $processWithError\n";
echo " File still exists: " . (file_exists($cleanupFile->toString()) ? "yes" : "no") . "\n";
// Clean up
if (file_exists($cleanupFile->toString())) {
unlink($cleanupFile->toString());
}
echo "\n";
// Example 11: Error handling with readLines
echo "11. Error handling with readLines:\n";
$linesResult = readLines($nonExistentFile)
->attempt()
->map(fn ($v) => $v->getOrElse([]))
->unsafeRunSync();
echo " Lines read (or empty): " . count($linesResult) . " lines\n\n";
// Example 12: Practical error handling pattern
echo "12. Practical error handling pattern:\n";
function readFileOrCreate(Path $path, string $defaultContent): string
{
return exists($path)
->flatMap(function ($fileExists) use ($path, $defaultContent) {
if ($fileExists) {
return readFileContents($path);
}
// File doesn't exist, create it with default content
return writeFileContents($path, $defaultContent)
->map(fn ($_) => $defaultContent);
})
->handleError(fn ($e) => "Error: " . $e->getMessage())
->unsafeRunSync();
}
$practicalFile = new Path(sys_get_temp_dir() . '/practical_test.txt');
$content1 = readFileOrCreate($practicalFile, "Initial content");
echo " First read (created): $content1\n";
$content2 = readFileOrCreate($practicalFile, "Initial content");
echo " Second read (existing): $content2\n";
// Clean up
if (file_exists($practicalFile->toString())) {
unlink($practicalFile->toString());
}
echo "\n";
echo "=== All error handling examples completed! ===\n";