Files and explicit errors
English | 日本語
Many operations return a value together with an Err. The presence of a value does not prove success: a result can retain partial progress.
Read a complete file
Create message.txt, then save this as read.gd:
func main():
var text, err = GD.file.read_text("message.txt")
if err != null:
printerr(err)
return 1
print(text)
return 0gd read.gdThe check distinguishes an empty file from an unreadable one. read_text decodes UTF-8; read_bytes preserves byte values.
Propagate a failure
Use ! when the current operation should fail if an API call fails:
func main():
GD.file.ensure_dir("output")!
GD.file.write_text("output/message.txt", "Hello!\n")!
return 0write_text replaces the file contents; append_text adds to the end. Their success values are not byte counts. In a function explicitly returning a value and Err, ? propagates a failed result to the caller.
Return your own error
A readable file can still be invalid for your application. Create an Err when the message is empty. Err("message", kind, details) takes a description, a kind such as Err.INVALID_DATA, and optional details. Save this as read_message.gd:
# Read a message and reject empty contents.
func read_message(path: String) -> String, Err:
var text := GD.file.read_text(path)?
if text.strip_edges().is_empty():
return "", Err("Message is empty", Err.INVALID_DATA, {"path": path})
return text, null
# Print the message or report the failure to the caller.
func main() -> int:
var text, err := read_message("message.txt")
if err != null:
printerr(err)
return 1
print(text)
return 0printf 'Hello!\n' > message.txt
gd read_message.gd
printf '' > message.txt
gd read_message.gdThe first run prints Hello!. After emptying the file, the second run reports Message is empty and exits with status 1.
-> String, Err declares a string and an error as the two return values. Return text, null on success and "", Err(...) on failure. The caller receives them with var text, err := read_message(...) and checks err before using text. If reading the file fails, ? returns that error to the caller directly.
Inspect the error value
Err exposes a kind, message and additional information. Use Err.find to locate a known cause instead of parsing message text. e.find({"source": "postgres", "code": "40001"}) matches details on one cause. e.note("operation", {"code": "E_0008"}) adds details while retaining the original cause.
Process large input
Use GD.file.open to obtain a stream and read chunks instead of allocating the entire file. Byte offsets and byte counts refer to encoded bytes, not text characters. Always close an owned stream when done, including when stopping early.
Permissions
The introductory commands use normal execution. For advanced isolation, --strict applies explicit access rules and mounts. Relative paths resolve under the execution directory; an absolute path is not an automatic permission grant. See the permissions manual before enabling strict mode in deployment.