|
|
|
|
|
by quantummagic
310 days ago
|
|
The idiomatic way in Zig is to return the simple unadorned error, but return detailed error data through a pointer argument passed into the function, allowing the function to fill in extra information before returning an error. const MyError = error{ FileNotFound, PermissionDenied };
fn readFile(path: []const u8, outErrInfo: *ErrorInfo) ![]const u8 {
if (fileMissing) {
if (outErrInfo) |info| {
info.* = ErrorInfo{
.code = MyError.FileNotFound,
.message = "File missing",
.line = @line(),
};
}
return MyError.FileNotFound;
}
return data; // success
}
The advantage of this is that everything is explicit, and it is up to the caller to arrange memory usage for error data; ie. the compiler does not trigger any implicit memory allocation to accommodate error returns. This is a fundamental element of Zig's design, that there are no hidden or implicit memory allocations |
|
Likewise, this has the disadvantage that the caller must allocate space for the error payload, even if the error is very unlikely