Repository navigation
Expand file tree
/
Copy patherror-handling.roc
More file actions
58 lines (45 loc) · 2.15 KB
/
Copy patherror-handling.roc
File metadata and controls
58 lines (45 loc) · 2.15 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
## Handle errors with tag-pattern matching.
app [main!] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.24.0/AEjfyaMFFbh8FJrkkHJy68riVNPr3Qp6c6PawWQjBwMH.tar.zst" }
import pf.OsStr
import pf.Stdout
import pf.Stderr
import pf.Path
main! : List(OsStr) => Try({}, _)
main! = |_args| {
file_name : Path
file_name = "test-file.txt"
# Try to read a file that doesn't exist - should error
missing_file : Path
missing_file = "nonexistent-file.txt"
# For professional software, use error tags (like `PathErr(NotFound, path)`) internally and convert
# them to a message for the user at the edge of your program. This also makes it easy to provide
# error messages in different languages.
match missing_file.read_utf8!() {
Ok(content) => Err(UnexpectedReadSuccess(content))?
# The failing path comes back with the error, so we can show it to the user.
Err(PathErr(NotFound, path)) => Stderr.line!("(Expected ✅) error: Path not found (NotFound): ${path.display()}")?
Err(PathErr(PermissionDenied, path)) => Stderr.line!("Unexpected Error: Permission denied for path:\n\t${path.display()}")?
Err(PathErr(Other(msg), path)) => Stderr.line!("Unexpected Error:\n\t${msg}\nFor path:\n\t${path.display()}")?
Err(err) => Stderr.line!("Unexpected Error: ${Str.inspect(err)}")?
}
directory : Path
directory = "examples"
match directory.read_bytes!() {
Err(PathErr(IsADirectory, path)) => Stderr.line!("(Expected ✅) error: Path is a directory: ${path.display()}")?
Ok(_) => Err(UnexpectedDirectoryReadSuccess)?
Err(err) => Err(UnexpectedDirectoryReadError(err))?
}
regular_file : Path
regular_file = "LICENSE"
match regular_file.list!() {
Err(PathErr(NotADirectory, path)) => Stderr.line!("(Expected ✅) error: Path is not a directory: ${path.display()}")?
Ok(_) => Err(UnexpectedFileListSuccess)?
Err(err) => Err(UnexpectedFileListError(err))?
}
file_name.write_utf8!("Hello from error-handling example!") ? |err| FileWriteFailed(err)
content = file_name.read_utf8!() ? |err| FileReadFailed(err)
# Cleanup
file_name.delete!() ? |err| FileDeleteFailed(err)
Stdout.line!("${file_name.display()} contains: ${content}")?
Ok({})
}