-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-handling.php
More file actions
73 lines (66 loc) · 2.08 KB
/
error-handling.php
File metadata and controls
73 lines (66 loc) · 2.08 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
<?php
/**
* Example 9: Error Handling
*
* Demonstrates how the library throws FileException for various error
* conditions: missing files, empty names/paths, invalid Base64, and
* end-of-file overruns.
*/
require_once __DIR__ . '/../../vendor/autoload.php';
use WebFiori\File\File;
use WebFiori\File\Exceptions\FileException;
// 1. Reading a file that doesn't exist
try {
$file = new File('/tmp/does-not-exist.txt');
$file->read();
} catch (FileException $e) {
echo "Error 1: " . $e->getMessage() . "\n";
// "File not found: '/tmp/does-not-exist.txt'."
}
// 2. Reading with no file name set
try {
$file = new File();
$file->read();
} catch (FileException $e) {
echo "Error 2: " . $e->getMessage() . "\n";
// "File name cannot be empty string."
}
// 3. Reading with name but no path (and file not in calling directory)
try {
$file = new File('nonexistent.txt');
$file->read();
} catch (FileException $e) {
echo "Error 3: " . $e->getMessage() . "\n";
// "Path cannot be empty string."
}
// 4. Writing with no data set
try {
$file = new File(__DIR__ . '/../tmp/empty-write.txt');
$file->create(true);
$file->write(false); // No data set via setRawData()
} catch (FileException $e) {
echo "Error 4: " . $e->getMessage() . "\n";
// "No data is set to write."
// Cleanup
(new File(__DIR__ . '/../tmp/empty-write.txt'))->remove();
}
// 5. Reading past end of file
try {
$file = new File(__DIR__ . '/../tmp/small.txt');
$file->create(true);
$file->setRawData('Short');
$file->write(false);
$file->read(0, 100); // File is only 5 bytes
} catch (FileException $e) {
echo "Error 5: " . $e->getMessage() . "\n";
// "Reached end of file while trying to read 100 byte(s)."
(new File(__DIR__ . '/../tmp/small.txt'))->remove();
}
// 6. Strict Base64 decoding with invalid characters
try {
$file = new File();
$file->setRawData('not@valid!base64', true, true);
} catch (FileException $e) {
echo "Error 6: " . $e->getMessage() . "\n";
// "Base 64 decoding failed due to characters outside base 64 alphabet."
}